- (NSManagedObjectContext *)anObjectByEntityForName:(NSString *)entityName withValue:(NSObject *)value forKeyPath:(NSString *)keyPath {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"%@ == %@", keyPath, value]];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (!mutableFetchResults) {
[request release];
[mutableFetchResults release];
return nil;
}
if ([mutableFetchResults count] == 0) {
[request release];
[mutableFetchResults release];
return nil;
}
id anObject = [mutableFetchResults objectAtIndex:0];
[request release];
[mutableFetchResults release];
return anObject;
}
此代码返回nil,键路径为“isSelected”,值为@YES。但是如果没有谓词,则返回所有对象。在数据库中,至少有一个符合条件的对象。惠特有什么问题?
答案 0 :(得分:4)
对于键或键路径,您必须使用%K格式:
[request setPredicate:[NSPredicate predicateWithFormat:@"%K == %@", keyPath, value]];
中