2012-06-21 50 views
1

我對iOS應用程序使用CoreData(NSManagedObject,UIManagedDocument),我想知道是否有可能獲取一組屬性。如何在iOS Core Data中獲取屬性數組?

例如,假設我有我的數據庫Person實體和每個Person有一個名爲income一個屬性,一個名爲name名。假設我的數據庫中有多個Person s。是否有可能獲取包含我的整個數據庫的所有收入的數組? (以每個人的收入作爲條目的陣列)。如果是這樣,我將如何按他們的名字對數組進行排序?

如果這是不可能的,你會如何建議我去完成這件事?我不想獲取整個Person實體,因爲還有很多其他大型屬性,例如images,這些屬性需要很長時間才能提取。

回答

2

您可以獲取你想要這樣的屬性:

NSFetchRequest* fetchRequest = [NSFetchRequest new]; 
fetchRequest.entity = <person entity description>; 
fetchRequest.propertiesToFetch = @[ @"name", @"income" ]; 
fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: YES] ]; 
fetchRequest.resultType = NSDictionaryResultType; 

NSError* error = nil; 
NSArray* personsAttributes = [managedObjectContext executeFetchRequest: fetchRequest error: &error]; 

personsAttributes看起來就像是:與ARC &文字

[ 
    { "name" : "Alfred", "income" : 1000 }, 
    { "name" : "Birgite", "income" : 2000 }, 
    … 
] 

代碼。您可能需要根據您的需求和編譯選項來調整它。

相關問題