Reputation: 503
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
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
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
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
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
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
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