Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the argument types on a block callback

I recently saw some example code in a WWDC video from an Apple engineer. He was using NSArray's enumerateObjectsUsingBlock: method, but I noticed the first argument to the block was not id as I'm used to, but had been changed to the concrete type that the developer knew was in the array.

For example, I just gave this a go in Xcode and everything works correctly:

NSArray *test = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
[test enumerateObjectsUsingBlock:^(NSString *aString, NSUInteger idx, BOOL *stop) {
    // ...
}];

The declaration for enumerateObjectsUsingBlock: declares the first block argument to be of type id:

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block

Now I understand that id can be used to represent any objective-c type, but this little trick with arguments was unknown to me.

Is there any documentation for this feature of the language? Can this be used in regular methods where you have an (id)sender argument too? Is this even safe or fully supported?

like image 453
Mike Weller Avatar asked Jun 09 '26 19:06

Mike Weller


1 Answers

Here's a link to apple doc about id type. This trick can be used in any method sending id, and it's safe, as long as you're sure about a type, or check it before you use it.

like image 122
ksh Avatar answered Jun 11 '26 09:06

ksh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!