Abhijeet
Abhijeet

Reputation: 503

How to check object is kind of block or not

How can we identify any particular object is kind of block or not?

for example,

NSSet *set =[NSSet setWithObjects:
             @"name1",
             @"name2",
             [^{ /* ..... some code */ } copy],
             nil];

How can we find out which object from set is kind of block?

Upvotes: 15

Views: 3207

Answers (6)

Micah Hainline
Micah Hainline

Reputation: 14427

There is a safer way to determine if something is a block without actually using private api or constructing a class using the private string name:

- (BOOL)isBlock:(id)item {
    id block = ^{};
    Class blockClass = [block class];
    while ([blockClass superclass] != [NSObject class]) {
        blockClass = [blockClass superclass];
    }
    return [item isKindOfClass:blockClass];
}

Upvotes: 12

Pierre Bernard
Pierre Bernard

Reputation: 3198

Wrap your block in a class of your own:

BlockWrapper *blockWrapper = [BlockWrapper wrapperWithBlock:^{ … }];

Check for the type and extract the actual block:

if ([obj isKindOfClass:[BlockWrapper class]]) {
    codeBlock = [(BlockWrapper*)obj block];
}

Upvotes: 7

al45tair
al45tair

Reputation: 4433

If you only have strings and blocks, just check ![thing isKindOfClass:[NSString class]]. i.e. invert your test.

Likewise, if you have strings, numbers and blocks, check that thing is not a string or a number, and in that case it must (by deduction) be a block. Either that, or your program is incorrect and will crash.

Upvotes: 2

user647562
user647562

Reputation:

I suppose that ![thing isKindOfClass:[NSObject class]], while not technically correct (you don't have to subclass NSObject), will probably get you want you want.

Upvotes: -3

omz
omz

Reputation: 53551

It's possible, but I wouldn't recommend doing this, because NSBlock is not a public class and its name might change in the future:

if ([obj isKindOfClass:NSClassFromString(@"NSBlock")]) {
    NSLog(@"It's a block!");
}

Upvotes: 2

Jens Ayton
Jens Ayton

Reputation: 14558

There is no supported way to do this. You must keep track of what objects are blocks, and what their type signatures are.

Do you have a practical use case for a set of mixed strings and blocks?

Upvotes: 2

Related Questions