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

- 22,706
- 18
- 63
- 99

- 1,112
- 1
- 14
- 32
-
1Objective-C isn't designed for this type of dynamism. I would suggest asking a question that focuses on a higher level description of what you are trying to do (across your multiple questions -- well posed questions, at that) and a runtime expert or two can chime in with details and suggestions. – bbum Jul 30 '12 at 14:01
2 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
Key Value Coding may be able to help you with this. There are primitives (e.g. valueForKey:
) which are able to inspect the object for ivars and perform conversions for builtins. In that sense, you would pass to the function the keys (ivar name as strings), and let the system perform the NSNumber
conversions where the types are C primitives. Of course, this would introduce some overhead.
You could also approach this using the objc runtime, but KVC will likely do what you need without needing to resort to using the objc runtime (yourself).
If you want to determine whether a va_list
parameter is a BOOL
, then you will need to specify it (that's why format specifiers are necessary). The alternative you see in some cases is -[NSArray initWithObjects:...]
-- in this case, the initializer requires objc objects for every parameter, as well as nil-termination; You would need to do a BOOL
->object promotion.
Alternative: C++ can provide all this type info for you (e.g. using templates).

- 104,054
- 14
- 179
- 226