开发者

Why is this IF block not being entered after checking against an NSManagedObject boolean property?

开发者 https://www.devze.com 2023-02-20 22:53 出处:网络
NSLog(@\"move report - %@\", [eventToArchive valueForKey:@\"archived\"]); if (![eventToArchive valueForKey:@\"archived\"]) {
NSLog(@"move report - %@", [eventToArchive valueForKey:@"archived"]);
if (![eventToArchive valueForKey:@"archived"]) {
   ....

The above code block is NEVER being entered, even though NSLo开发者_开发问答g returns

move report - 0

Every single time it runs?

Do I need to do something like,

if (![NSNumber numberWithBool:[eventToArchive valueForKey:@"archived"]]) {

?


The reason that the conditional block is never entered is that -valueForKey: returns an id, which is to say a pointer. You're using it as though it were a BOOL, however, so the only way you'll ever enter that block is if -valueForKey: returns nil.

Your log statement prints "0" as the value because you used the object format specifier, %@, which expects a pointer and prints a description of the object that the pointer points to. You're probably giving it a NSNumber*, and it's properly printing the value represented by that object.

The preceding two answers are correct in pointing out that you should use the -boolValue method to get a BOOL value from the NSNumber that you get from -valueForKey:.


This should work

if (![[eventToArchive valueForKey:@"archived"] boolValue])

boolValue works on NSStrings and NSNumbers so if the archived property of eventToArchive is a BOOL, Key Value Coding will automatically convert that into a NSNumber for you.


Assuming that 'archived' is a boolean property on a subclass of NSManagedObject you need to do;

if(![eventToAcrhive.archived boolValue]) {
    // not archived
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号