For the iOS app I’m working on, I’m currently writing a singleton class that handles asynchronous requests to a server. Here’s an example of one of the methods –
- (void)registerUser:(CBCUserRegistration *)userRegistration delegate:(id)<CBCUserRegistrationDelegate>delegate;
within this method, an NSURLConnection is created and sends an asynchronous request. At this point, i need a way to tie the delegate object to the NSURLConnection, so thats when
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
is called, I know which delegate to inform. Because the requests are asynchronous, there may be more than one request going at any time. My initial though was to use an NSMutableDictionary, setting the NSURLConnection as the key and the delegate as the value, but the keys are copied so thats a no go. Can anyone suggest another way to track this?
Thanks in advance.
Avoid using an NSDictionary for this. Instead take an object-oriented approach:
Write a class
MyConnectionthat implements the requiredNSURLConnectionDelegatecallbacks and has a property/ivar of theid<CBCUserRegistrationDelegate>type. Add astartmethod toMyConnectionthat creates anNSURLConnection, assigns itself a delegate of that connection, and starts it. Now you can create an instance ofMyConnectionfor every URL request you do.MyConnectionkeeps hold of theCBCUserRegistrationDelegateand forwards the result it receives from theNSURLConnection.However, using delegate here is a bit old-fashioned. Use blocks instead, especially if your project uses ARC.
NSURLConnectionprovides a convenient method to do async requests:[NSURLConnection sendAsynchronousRequest:queue:completionHandler:].For example: