How to get BOOL from id

21,579

Solution 1

-valueForKey: always returns an object. id is the objective-c type for pointer to any object.

You can examine the object in the debugger. Some useful commands:

po value
po [value class]

You'll find that the value is actually an NSNumber, so you can send it the -boolValue message to get the BOOL flag you are interested in.

Solution 2

//value = (id)
NSNumber *val = value;
BOOL success = [val boolValue];
if (success) {
 //yay!
}

Solution 3

If the value of the key is a BOOL, then the returned object will be an NSNumber. You can just ask it for its boolValue. You can't simply cast from an object (id) to a BOOL or integer or any other non-object type. The KVC machinery autoboxes scalars into the appropriate value type, so you can just ask it for the type you want. You might be interested in the KVC docs — they explain this in more detail.

Solution 4

Easier? Perhaps not. More terse? Not when you asked, but in modern (since at least 2015) Obj-C, yes. If your object is a dictionary with string or number values (NSDictionary<id, StringOrNumber>) of any sort, you can use:

BOOL value = @(managedObject[@"fieldName"]).boolValue;

Note that, also, if you know the value you get from @"fieldName" is a NSNumber, you can just skip the conversion:

BOOL value = [managedObject[@"fieldName"] boolValue];

Why?

Thanks to some changes in the LLVM compiler:

  • NSDictionarys can now be read and written using the familiar dictionary[key] syntax
  • Compatible values can be turned into NSNumbers using the @(value) syntax. more
  • All properties (and methods that take zero arguments and return a value) can be accessed using dot-syntax: object.property and object.method.

There's a lot of nice syntactic sugar, now. I recommend you look into it!

Share:
21,579
Justin Kredible
Author by

Justin Kredible

Updated on May 23, 2020

Comments

  • Justin Kredible
    Justin Kredible almost 4 years

    I'm calling valueForKey on an object. This returns an id which I tried to cast to a BOOL (because I know the value is a BOOL). But XCode gives the following warning:

    "warning: cast from pointer to integer of different size..."

    So what I ended up doing was this:

    BOOL value = [[NSNumber numberWithInt:((NSInteger)[managedObject valueForKey:@"fieldName"])] boolValue];
    

    I'm thinking that there must be an easier way. Is there?

  • quellish
    quellish almost 11 years
    Actually, the result is in the NSNumber class cluster. The curious thing in this case is that it returns a bare NSNumber, not an NSCFBoolean.