我正在尝试更新存储在核心数据实体中的布尔值,无论我尝试什么,它似乎都不会更新。这是我正在使用的方法:
+ (void) updateTimeFormatPreferenceForUserWithNumber:(NSString *)number withBool:(BOOL)preference WithContext:(NSManagedObjectContext *)context {
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mobileNumber == %@", number];
[fetchRequest setPredicate:predicate];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"User" inManagedObjectContext:context]];
[fetchRequest setIncludesPropertyValues:YES];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if ([result count] > 0){
User *user = [result objectAtIndex:0];
[user setTwentyFourHourTime:[NSNumber numberWithBool:preference]];
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
} else {
BOOL twentyFourHour = [[CoreDataUtils getUserWithNumber:number WithContext:context] twentyFourHourTime];
NSLog(@"Saved Preference %s", preference ? "True" : "False");
NSLog(@"From user object: %@", [user twentyFourHourTime]);
NSLog(@"Twenty Four Hour Time is: %s", twentyFourHour ? "true" : "false");
}
}
}
使用preference属性调用此方法,因为true和false都具有以下输出:
Saved Preference False
From user object: 0
Twenty Four Hour Time is: true
Saved Preference True
From user object: 1
Twenty Four Hour Time is: true
Saved Preference False
From user object: 0
Twenty Four Hour Time is: true
Saved Preference True
From user object: 1
Twenty Four Hour Time is: true
二十几岁的布尔永远不会改变,它让我疯狂,为什么不更新?
getUserWithNumber方法是:
+ (User *) getUserWithNumber:(NSString *)number WithContext:(NSManagedObjectContext *)context {
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mobileNumber == %@", number];
[fetchRequest setPredicate:predicate];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"User" inManagedObjectContext:context]];
[fetchRequest setIncludesPropertyValues:YES];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if ([result count] > 0){
return [result objectAtIndex:0];
} else {
return nil;
}
}
三江源
答案 0 :(得分:2)
这一行
BOOL twentyFourHour = [[CoreDataUtils getUserWithNumber:number WithContext:context] twentyFourHourTime];
不正确,因为您正在将NSNumber
个实例保存到BOOL
变量中,因此您确实在测试是否已设置该数字而不是bool的值。将其更改为
BOOL twentyFourHour = [[[CoreDataUtils getUserWithNumber:number WithContext:context] twentyFourHourTime] boolValue];