Search code examples
propertiesnsurlconnectiondelegationnsurlconnectiondelegate

How to access NSURLConnection Delegate property


Why is it not possible to do the following:

id connectionDelegate = myConnection.delegate;
//myConnection is an instance of NSURLConnection

Why is this not possible, and how do I access the delegate otherwise. Seems rather awkward to me, or am I missing something here?


Solution

  • NSURLConnection is pretty awkward. Why are you still using it? Unless you're trying to maintain backwards compatibility with iOS 6 or OS X v10.8 and earlier, just use NSURLSession.

    With that said, if you must keep using that API for backwards compatibility, you can always do what I've done in these situations:

    • Create category methods called delegate and setDelegate.
    • Use Objective-C associated objects to store and retrieve the value on the connection object.
    • If you aren't in control of the code that creates the NSURLConnection objects, swizzle the NSURLConnection class's init methods to call your setter. Otherwise, just call the setter manually right after you create the NSURLConnection object.