Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if ivar is BOOL

I have a method where I'm passing a variable list of arguments. I do isKindOfClassfor strings, etc. However how can I determine if an ivar is a BOOL?

like image 392
John Lane Avatar asked Jul 30 '12 10:07

John Lane


1 Answers

No, not at runtime. BOOL is a primitive type, not a class. Actually BOOL is a signed char.

typedef signed char     BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED


#define YES             (BOOL)1
#define NO              (BOOL)0

As a workaround you can wrap a BOOL in a NSNumber to make an Obj-C object from it. Then you can do runtime checks:

NSNumber * n = [NSNumber numberWithBool:YES]; // @(YES) in Xcode 4.4 and above
if (strcmp([n objCType], @encode(BOOL)) == 0) {
    NSLog(@"this is a bool");
} else if (strcmp([n objCType], @encode(int)) == 0) {
    NSLog(@"this is an int");
}

EDIT: this code may not work for BOOL because it is encoded as char internally. Refer to this answer for an alternative solution: https://stackoverflow.com/a/7748117/550177

like image 89
Felix Avatar answered Oct 16 '22 23:10

Felix