2012-03-11 54 views
1

這個問題聽起來像一個新手,但我已經通過所有線程爲我的解決方案,這仍然是我的問題。所以我有一個實體「LookUp」,它有一個屬性「descrip」。 現在我的問題是我想獲取屬性'descrip'的所有值。通過CoreData中的NSPredicate獲取屬性的所有值

到現在我已經用這一切的疑問:

[NSPredicate predicateWithFormat:@"descrip == %@",[NSNumber numberWithInt:1]]; 
[NSPredicate predicateWithFormat:@"descrip == %@",@"descrip"]; 
[NSPredicate predicateWithFormat:@"descrip == %@",[NSNumber numberWithBool:YES]]; 

如果我火查詢

[NSPredicate predicateWithFormat:@"descrip == %@",@"Art Gallery"]; 

它返回我與「藝術畫廊」相關聯的值的數組。 'descrip'屬性包含250個值,如「Art Gallery」。

請幫幫忙。提前致謝。

+0

您是否試過[NSPredicate predicateWithFormat:@「descrip ==%@」,@「%」];?你只想要descrip的獨特價值? – Ravin 2012-03-11 15:28:50

+0

它不適合我。 – iamsult 2012-03-12 05:52:04

回答

2

NSPredicate是用來限制你的結果到堅持一定的限制的實體 - 就像你說的,記述== @「藝術畫廊」將返回有decrip屬性設置爲所有實體美術館

就你而言,你不想限制查詢中的實體。只需執行沒有任何謂詞的查詢,並返回所有實體。現在只要遍歷所有的實體,並獲得記述的所有值成的NSMutableSet的NSMutableDictionary,你有你記述值的列表。

+0

感謝upvote並接受。 – iamsult 2012-03-12 09:34:58

0

您還可以設置請求

[request setResultType:NSDictionaryResultType]; 
[request setPropertiesToFetch: 
    [NSArray arrayWithObject: @"descrip"]; 

但你還是要循環的結果陣列上,以只搶記述值。

1

您可能想修改提取請求,而不是謂詞。見"Fetching Distinct Values" in Apple's Core Data Snippets

NSManagedObjectContext *context = // Get the context. 

NSEntityDescription *entity = [NSEntityDescription entityForName:@"LookUp" inManagedObjectContext:context]; 

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entity]; 
[request setResultType:NSDictionaryResultType]; 
[request setReturnsDistinctResults:YES]; 
[request setPropertiesToFetch:@[@"descrip"]]; 

// Execute the fetch. 
NSError *error; 
id requestedValue = nil; 
NSArray *objects = [context executeFetchRequest:request error:&error]; 
if (objects == nil) { 
    // Handle the error. 
}