Determine if ivar is BOOL

I have a method where I pass a list of variables. I am making isKindOfClass for strings, etc. However, how can I determine if ivar is BOOL?

+6
source share
2 answers

No, not at runtime. BOOL is a primitive type, not a class. In fact, 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 BOOL in NSNumber to create an Obj-C object. Then you can perform 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 as it is encoded as char internally. Refer to this answer for an alternative solution: fooobar.com/questions/162596 / ...

+4
source

Coding key values ​​can help you with this. There are primitives (e.g. valueForKey: that can validate an object for ivars and perform conversions for inline ones. In this sense, you must pass functions to the keys (the ivar name as strings) and let the system perform NSNumber conversions, where types are C primitives. Of course, this will lead to some overhead.

You can also come close to this using objc runtime, but KVC will most likely do everything you need without resorting to using the objc runtime (on its own).

If you want to determine if the va_list parameter is BOOL , then you will need to specify it (therefore formatting specifiers are needed). An alternative that you see in some cases -[NSArray initWithObjects:...] - in this case, the initializer requires objc objects for each parameter, as well as nil-term; You will need to do the promotion object BOOL β†’.

Alternative: C ++ can provide you with all this information (e.g. using templates).

0
source

Source: https://habr.com/ru/post/921661/


All Articles