Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using performSelector: to access BOOL property

I am using performSelector:, which returns an id object, to call several other methods. The return type of those methods can actually be either be a BOOL, int, NSDate or any other kind of object.

How can I figure out whether the object returned from performSelector: is a BOOL or not? I tried converting it to a NSNumber and such, but this crashes if the object is not a BOOL.

I have a class with attributes such as these:

@property(retain,nonatomic) NSString* A;
@property(assign,nonatomic) BOOL B;
@property(retain,nonatomic) NSArray* C;
@property(assign,nonatomic) int64_t D;

This class is generated by a framework, so I cannot change it. But I want to loop over A, B, C, D to call each attribute and retrieve the data. However, as you can see, the return type can vary and I need to adjust to that.

I am doing something similar to:

SEL s = NSSelectorFromString(@"A");
id obj = [object performSelector:s];
//check if obj is BOOL
//do something with obj
like image 969
Se7enDays Avatar asked Jan 15 '23 10:01

Se7enDays


1 Answers

If all you need to do is obtain the values of various properties, use key-value coding, which automatically wraps scalar types such as int and BOOL in instances of NSNumber. So all you would need would be a line like the following:

id value = [object valueForKey:@"somePropertyName"];

Otherwise, you could check ahead of time for the return type by calling methodSignatureForSelector: on the target object, but that seems like a bunch of unnecessary work given the situation you described.

like image 63
jlehr Avatar answered Jan 25 '23 01:01

jlehr