user
user

Reputation: 3456

How can I pass a parameter to a delegate callback method?

This seems really odd, so I doubt it's good practice but I'm working on an old app and I need to make some updates without totally redesigning the whole thing.

Currently, I have a UIButton which has an outlet as

- (IBAction) toggleBroadcast:(UIButton*) sender 
{
   // configure and start video capture
}

But I'm trying to implement remote configuration which makes a call to a php script with the device id and returns a (JSON parsed to) NSDictionary, which is loaded into a static config class.

Since networking requires asynchronous delegate methods and my // configure and start video capture code is dependent on the network-retrieved data, I have to make my toggleBroadcast function look like:

- (IBAction) toggleBroadcast:(UIButton*) sender 
    {
       // get identifier, fill request...
       // NSURLConnection* connection = [NSURLConnection connectionWithRequest:request
                                                                      delegate:self];
    }

and the connectionDidFinishLoading delegate method then calls my original toggleBroadcast code, which is now encapsulated separately so it can be called at the appropriate time.

BUT! I need that sender.

So how can I send sender as a parameter to my delegate method so I can send it to my new

- (void) originalToggleBroadcastCode:(UIButton*) sender?

Upvotes: 1

Views: 340

Answers (2)

Mike Pollard
Mike Pollard

Reputation: 10195

You could use the very nice BlocksKit library which would then allow you to do:

- (IBAction) toggleBroadcast:(UIButton*) sender 
{
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request];

    connection.successBlock = ^(NSURLConnection *connection, NSURLResponse *response, NSData *responseData){
         [self originalToggleBroadcastCode:sender];

    [connection start];
 };

Upvotes: 1

Nick
Nick

Reputation: 2369

to accomplish what you're asking, you could try creating an NSOperation subclass that accepts a UIView as an argument. This operation could perform the request, and then update the UIView when done. (be sure to do the UI update on the main thread). This seems like a strange design pattern though.

personally, I would have my view controller subscribe to notifications, and then send out a notification when the download is done. you can store info about the operation's success or failure in the userInfo dictionary that is stored in the NSNotification object, and respond appropriately. Again, be sure to send the completion notification on the main thread.

Upvotes: 1

Related Questions