核心数据获得特定对象

时间:2013-04-01 23:15:31

标签: ios core-data ios6.1

- (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。但是如果没有谓词,则返回所有对象。在数据库中,至少有一个符合条件的对象。惠特有什么问题?

1 个答案:

答案 0 :(得分:4)

对于键或键路径,您必须使用%K格式:

[request setPredicate:[NSPredicate predicateWithFormat:@"%K == %@", keyPath, value]];

显示在Documentation