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;
}

对于键路径“isSelected”和值@YES,此代码返回 nil。但如果没有谓词,则返回所有对象。在数据库中至少有 1 个符合条件的对象。whit有什么问题?

4

1 回答 1

4

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

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

显示在文档中

于 2013-04-01T23:18:50.283 回答