我的数据库中有一个名为“Me”的实体,它有一个名为“loggedIn”的BOOL属性。我将属性的默认值设置为NO,如下所示:
为了确保它设置为NO,我还以编程方式设置它,但它仍然在日志中显示为YES:
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Me"];
NSError *err;
NSUInteger count = [context countForFetchRequest:request error:&err];
if (count == 0) {
NSManagedObject *me = [NSEntityDescription insertNewObjectForEntityForName:@"Me" inManagedObjectContext:context];
}
NSArray *fetchedObjects = [context executeFetchRequest:request error:&err];
[[fetchedObjects objectAtIndex:0] setValue:[NSNumber numberWithBool:NO] forKey:@"loggedIn"];
NSString *amIYesOrNo = [NSString stringWithFormat:@"%@", ([[fetchedObjects objectAtIndex:0] valueForKey:@"loggedIn"] ? @"YES" : @"NO")];
NSLog(amIYesOrNo);
amIYesOrNo当它应该为NO时总是显示YES。发生了什么事?
答案 0 :(得分:4)
valueForKey:@“loggedIn”正在向您返回一个有效对象,然后您的?:运算符正在检查它是否为非零且始终为。您需要对NSNumber应用boolValue方法调用以获取它包含的内容。