Re: Stupid block syntax!
Re: Stupid block syntax!
- Subject: Re: Stupid block syntax!
- From: Ken Thomases <email@hidden>
- Date: Wed, 04 Jul 2012 01:12:12 -0500
On Jul 4, 2012, at 12:40 AM, Graham Cox wrote:
> Why doesn't this compile?
>
>
> NSComparisonResult (^comp)( id<DKStorableObject>, id<DKStorableObject> ) = ^( id<DKStorableObject> a, id<DKStorableObject> b )
> {
> if( a.index < b.index )
> return NSOrderedAscending;
> else if ( a.index > b.index )
> return NSOrderedDescending;
> else
> return NSOrderedSame;
> };
>
> error: incompatible block pointer types initializing 'NSComparisonResult (^)(id<DKStorableObject>, id<DKStorableObject>)' with an expression of type 'int (^)(id<DKStorableObject>, id<DKStorableObject>)'
>
> Why does it assume that the return type is 'int"? There is nothing here that appears to suggest it is one.
Yes, there is. NSOrderedAscending, NSOrderedDescending, and NSOrderedSame are elements of an enum. They are effectively ints.
> NSComparisonResult is a typedef of NSInteger.
Right, but the elements of the enum are not of type NSComparisonResult. In traditional C, there's no way to declare the type of elements of an enum. There's a coming extension to the language in clang that addresses this. <http://clang.llvm.org/docs/LanguageExtensions.html#objc_fixed_enum> I don't know what version of Xcode includes or will include this. Even when it arrives in the compiler, the SDK will have to be updated to take advantage of it.
> If I attempt to cast the result, I get an equally baffling error:
Cast what result? I bet if you cast the value in each return statement, that would work.
> error: invalid block pointer conversion initializing 'NSComparisonResult (^)(id<DKStorableObject>, id<DKStorableObject>)' with an expression of type 'NSComparisonResult' (aka 'long')
Sounds like you tried to cast the block reference to an NSComparisonResult. Roland has suggested the syntax for explicitly declaring the return type of the block, which is not a cast as such. It just means the compiler doesn't have to / get to infer it from the return statements within the block.
> Could the stupid block syntax be any less intuitive?
It follows the general form for C declarations, such as for function pointers. However, blocks can be defined in different contexts than functions, which makes it seem out of place. In general, try writing it exactly as though you were writing a function. Then replace the function name with either "^" or, when defining a variable or typedef, "(^name_of_variable_or_typedef)".
Regards,
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