Re: blocks and id
Re: blocks and id
- Subject: Re: blocks and id
- From: Gwynne Raskind <email@hidden>
- Date: Wed, 12 Dec 2012 07:01:50 -0500
On Dec 12, 2012, at 6:36 AM, email@hidden wrote:
> On 12 Dec 2012, at 09:57, Andreas Grosam <email@hidden> wrote:
>> On 12.12.2012, at 10:19, Charles Srstka wrote:
>>> On Dec 12, 2012, at 3:03 AM, Andreas Grosam <email@hidden> wrote:
>>>
>>>> How can I check at runtime whether an object (id) is actually a block, and not another kind of object?
>>>
>>> I don't think there's any good way of doing that right now. You could check the class of the block, but since the block classes are completely undocumented AFAIK, there's no guarantee that the class names won't change in some future release of OS X and break your code.
>> Thanks for the reply. I feared that.
>>
>> Currently, I resort to
>>
>>
>> if ([obj isKindOfClass: NSClassFromString(@"NSBlock")])
>> …
>>
>> which evaluates to YES if `obj` is a block. However, NSBlock is not a public class, thus: NSClassFromString(@"NSBlock") which "works" as the time of writing in Mac OS, and returns a class whose name is "NSBlock" (the real block classes are named differently).
>>
>> I wish there was something official.
> You could perhaps make this a little less fragile.
>
> typedef void (^MyBlockType)(void);
>
> // we know this is a block
> void (^isaBlock)(void) = ^(void) {};
>
> MyBlockType aBlock = ^(void) {NSLog(@"I am a block");};
>
> id qua = aBlock;
>
> if ([qua isKindOfClass:[isaBlock class]]) {
> ((MyBlockType)qua)();
> }
This will not work for all cases. For example, a stack-based block versus one that's been copied to the heap will have different classes, which are probably siblings (i.e. [[_NSConcreteStackBlock class] isKindOfClass:[_NSMallocBlock class]] == NO).
My solution to this issue has been the "exclusion" case, i.e. if (![obj isKindOfClass:[anything my API contract says I can receive that isn't a block]]) { /* it's a block by process of elimination */ }. Obviously this won't work if your API contract says you can receive arbitrary objects.
-- Gwynne Raskind
_______________________________________________
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