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?
Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.
To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. For example, you can use the TypeOf… Is construct in Visual Basic or the is keyword in C#. The GetType method is inherited by all types that derive from Object.
In the main method, we created an object of the User2 class using the new keyword and called the getUser1Object() method. It returns an object of class User1 , which we later store in getUser1Object . To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter.
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];
}
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];
}
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?
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!");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With