2013-04-01 206 views
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; 
} 

對於keypath「isSelected」和值@YES,此代碼返回nil。但是如果沒有謂詞,則返回所有對象。在數據庫中至少有1個符合條件的對象。什麼可能是錯誤的惠特?核心數據獲取特定對象

回答

4

鑰匙或關鍵路徑,你必須使用%K格式:

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

所示Documentation

+0

哇,這是那麼容易......你有任何文檔,這對蘋果文檔? –

+1

已包含文檔鏈接的更新答案:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-SW2 – bvogelzang

相關問題