How to write a valid boolean conditional in objective-c using objectForKey
I'm seeking to unders开发者_开发知识库tand why the following always hits the ELSE clause. What I can't figure out is that regardless of the actual value ( NSLog shows a 0 or 1) this always hits the else. Any reason why?
The item NSArray is pulled from a JSON object -fyi
BOOL* instock = [item objectForKey:@"itemInStock"];
obj.instock = instock;
NSLog(@"and it was %@", obj.instock);
if (obj.instock == YES) {
//do yes stuff
}else {
//do no stuff
}
Your code here is rather strange. What is the type of obj.instock
? Your very first line
BOOL* instock = [item objectForKey:@"itemInStock"];
makes no sense at all. -objectForKey:
doesn't return BOOL*
values. It returns id
. I'm guessing here that you're actually getting an NSNumber *
back, and it just happens to work alright because an NSNumber *
fits inside of a BOOL *
(as they are both pointers). Similarly, obj.instock
is likely to be an NSNumber*
as well (if it wasn't an object of some sort, your NSLog()
would crash).
So, assuming that obj.instock
is an NSNumber*
, the conditional you want is simply
if ([obj.instock boolValue]) {
// yes
} else {
// no
}
You should also fix this code to not try and claim you have a BOOL*
when you don't.
In your NSLog
, you are using %@
.
%@
refers to objects. Contrary to your BOOL* instock
which is not an object.
There are ways to fix that.
What data type does your [item objectForKey:@"itemInStock"];
return?
If it returns an NSNumber for example, then you can do:
obj.instock = [[item objectForKey:@"itemInStock"] boolValue];
NSLog(@"and it was %d", obj.instock);
if (obj.instock == YES) {
//do yes stuff
}else {
//do no stuff
}
Again, there are other ways to do that.
精彩评论