Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get BOOL from id

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?

like image 488
Justin Kredible Avatar asked Aug 05 '09 01:08

Justin Kredible


3 Answers

-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.

like image 145
Jim Correia Avatar answered Nov 14 '22 05:11

Jim Correia


//value = (id)
NSNumber *val = value;
BOOL success = [val boolValue];
if (success) {
 //yay!
}
like image 27
fulvio Avatar answered Nov 14 '22 03:11

fulvio


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.

like image 9
Chuck Avatar answered Nov 14 '22 04:11

Chuck