Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Completion Handler in Variable iOS (Objective c)

I need to do a repeating task with the result of an http request and so would like to store the declaration of the completion hander in a variable (or somehow declare it as a function that can be passed in).

Example code:

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
   // carry out some action
 }];

I would like to be able to write

   [NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler: standardHandler ];

Where standardHandler contains a block function.

Is this possible?

I'm quite new to Objective C so sorry if this is an obvious question.

like image 243
Ciaran Fisher Avatar asked Feb 22 '26 23:02

Ciaran Fisher


1 Answers

Sure:

void (^completionHandler)(NSURLResponse *, NSData *, NSError *) = ^(NSURLResponse *response, NSData *data, NSError *error) {
    // carry out some action
};
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:completionHandler];
like image 125
rist Avatar answered Feb 24 '26 12:02

rist