2010-11-23 38 views
1

假設我有一個名爲Person的核心數據實體。我如何得到一個屬性匹配某些值的人的NSArray?例如某人在特定的年齡,身高,體重或者...或者有人用其身高,體重和年齡是特定值...使用NSPredicate獲取Core Data對象的數組?

我可以使用NSPredicate像這樣:

NSPredicate *pred = 
[NSPredicate predicateWithFormat: 
@"(age == 25) OR (height_in_cms == 185) OR (age == 30 AND height_in_cms == 170 AND weight_in_kgs == 80)"; 
// All properties are NSNumber 

回答

1

我不是在語法predicateWithFormat:的專家,但已經具備了基本依據。您可以在Apple的Predicate Programming Guide中找到有關格式的詳細信息。如果你問到與謂詞做,一旦你擁有了它,這裏是你展示的步驟片段:

// Create a fetch request. 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

// Set the entity for the fetch request. 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:managedObjectContext]; 
[fetchRequest setEntity:entity]; 
[entity release]; 

// Set the predicate for the fetch request. 
[fetchRequest setPredicate:predicate]; 

// Perform the fetch. 
NSError *error; 
NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
[fetchRequest release]; 

如果你想要的結果進行排序,你可以通過排序描述符的數組在執行提取之前使用setSortDescriptors:對提取請求進行提取。

1

如果你在變量中有這些值,你可以按照給定的語句。 [fetchResults filterUsingPredicate:[NSPredicate predicateWithFormat:@「age ==%i OR hieght ==%i and weight ==%i」,age,height,weight]];};}};}};

,也是你的做法是對的情況下的特定值正確的,但有你的語句的語法錯誤,以便保持適當的語法

相關問題