2012-11-22 35 views
0

我在我的Iphone應用程序中使用核心數據。在我的核心數據我有類似的東西;Objective-C,核心數據問題

[對象:表,數:2]

[對象:表,數:4]

[對象:窗口,編號:2]

[對象:窗口,編號: 5]

[對象:椅子,編號:2]

[對象:椅子,數:3]

我怎樣才能得到一個NSArray與表的最低號碼,窗口的最低號碼和椅子的最低號碼?謝謝。

回答

2

從蘋果網站

https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html

1)直取指定你想獲得

NSManagedObjectContext *moc = [self managedObjectContext]; 
NSEntityDescription *entityDescription = [NSEntityDescription 
    entityForName:@"Employee" inManagedObjectContext:moc]; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entityDescription]; 

2)指定您正在尋找的特點酒色實體的類型,(你可以忽略這一點,因爲你想所有)

// Set example predicate and sort orderings... 
NSNumber *minimumSalary = ...; 
NSPredicate *predicate = [NSPredicate predicateWithFormat: 
    @"(lastName LIKE[c] 'Worsley') AND (salary > %@)", minimumSalary]; 
[request setPredicate:predicate]; 

3)spe cify的命令

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
    initWithKey:@"firstName" ascending:YES]; 
[request setSortDescriptors:@[sortDescriptor]]; 

NSError *error; 
NSArray *array = [moc executeFetchRequest:request error:&error]; 
if (array == nil) 
{ 
    // Deal with error... 
} 

4)你得到一個排序的數組,所以...得到最後或第一個條目,取決於你選擇的順序。

+0

對不起,我問我的問題不好。我編輯它。 – tchike

+1

如果表,窗口和椅子是不同的實體,那麼你可以按照上述相同的方式爲它們提取,如果它們是相同的實體,你可以使用謂詞來獲取3次,以搜索類似於@「type = chair」的東西其餘的答案是相同的,或者你可以像上面和數組內部一樣對它進行排序,以便在數組中找到一個簡單的for循環,當你找到3中的第一個時,搜索3中的任何一個,一個,然後你繼續通過數組,直到你得到這種類型的其他2個第一個對象。 – Pochi

+0

他們在同一個實體中。我會這樣做,謝謝。 – tchike