Re: Is substitution of block-function parameters OK when it's an object type?
Re: Is substitution of block-function parameters OK when it's an object type?
- Subject: Re: Is substitution of block-function parameters OK when it's an object type?
- From: Ken Thomases <email@hidden>
- Date: Tue, 05 Aug 2014 17:06:22 -0500
On Aug 5, 2014, at 11:38 AM, Daryle Walker <email@hidden> wrote:
> Some code I just wrote to implement history menus for my browser’s back and forward buttons:
>
> [[backForwardList backListWithLimit:(int)maxMenuLength] enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(WebHistoryItem *obj, NSUInteger idx, BOOL *stop){
>
> The type of “obj” was originally “id,” but I changed it to what I knew the NSArray object actually held. The compiler accepted it. Can I change any block parameter, or only ones that are Objective-C objects? (For example, would changing the type of “idx” or “stop” cause errors?) What happens if I use the wrong Objective-C type?
Two things:
1) Older versions of the compiler used to complain about the mismatched block types. I think the loosening of that rule was deliberate, so I think this technique is blessed by the compiler designers.
2) The alternative would often be to do something like this:
[[backForwardList backListWithLimit:(int)maxMenuLength] enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
WebHistoryItem* historyItem = obj;
// …work with historyItem instead of obj…
Note that there's no question whether that's valid. It is. There's no need for a cast. Assuming that you know the collection really does contain WebHistoryItem instances, it's safe and correct.
So, since this is effectively the same thing as what you wrote above, just more verbose and cumbersome, I think that's why the compiler designers decided it was safe to loosen that rule.
Cheers,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden