Reputation: 53
In Objective-C is it possible to use a method in lieu of a block?
So for example, in stead of defining a block then calling the method:
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) {
[self processTwitterSearchResponse:response data:responseData error:error];
}
];
Call the method directly:
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:(processTwitterSearchResponse:response data:responseData error:error)
];
Or some such.
Upvotes: 2
Views: 151
Reputation: 53000
It's a sensible question, just to add a little to the answers already given.
If you look at method which directly accepts another method as an argument you will note that it also takes an additional argument, the object to call the method on. Look at your block example and you will see it references self
, so your block is providing the same pair of values - a method and an object.
There is absolutely no reason why Objective-C could not have a construct which took an object and a method, say @block(object, method)
or even more simply just object.method
, and returned a block but it does not have. If you are familiar with C# you will know it does have such a construct to produce a delegate, which is its version of a block.
Upvotes: 1
Reputation: 27900
In a word, no.
If the method is expecting a block, that's what you have to give it.
One way to understand this: blocks capture state (values of variables) from the place (lexical scope) where they are defined, allowing that state to be passed to another thread for deferred execution. That's why they are not interchangeable with a function pointer; there's more information being carried along with a block.
Upvotes: 1
Reputation: 57149
Nope. If the method takes a block as its handler, you need to give it a block. Why?
There are some methods that take function pointers instead of blocks, like NSArray’s -sortedArrayUsingFunction:context:
(as opposed to the block-based -sortedArrayUsingComparator:
), but you definitely can’t just swap in a method signature where it expects a block.
Upvotes: 1