2014-07-13 61 views
0

我的核心數據對象是這樣的:獲取與秩序

Person 
------- 
presonId 
name 

現在假設我得到的personsIds數組,我想獲取所有Person對象包括本personsIds陣列。

所以我的讀取請求將是:

NSArray *personsIds = [self getPersonsIds]; 

// fetch all persons with ids in personsIds 
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; 
request.predicate = [NSPredicate predicateWithFormat:@"presonId in %@", personsIds]; 
NSArray *results = [self.context executeFetchRequest:request error:&anyError]; 

現在我的問題是這樣的:
personsIds的順序是非常重要的,我想的是,results陣列將在相同的順序進行排序。

我無法與personId陣列混亂,無法對其進行排序或什麼..

公告稱,personsIds陣列可以有更多的對象比results陣列

回答

0

您可以排序取要求與NSSortDescriptor結果:

NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"personId" ascending:YES]; 

request.sortDescriptors = [NSArray arrayWithObjects:@[sort1, sort2]]; 

如何排序的描述應該看起來像取決於你怎麼想的結果進行排序。這取決於你的personIds數組是如何排序的。

如果你不能用這種一般的方式來描述排序,你將需要遍歷結果並手動排序。

+0

這個問題是我的PERSONID陣心不是排序,但它的順序很重要,所以我不能排序。我需要的結果與我的personId數組的結果是一樣的。也許我不應該在這裏使用字排序..不適當更新我的問題 – Eyal

+0

然後,你需要通過循環結果和排序像personIds數組排序自己排序自己。 – Cornelius

0

正如Cornelius所說,您使用排序描述符。在你的情況下,排序被定義爲「按照其他列表的順序」。因此,我們需要一種方法將personId映射到「原始列表中的索引」中,然後對其進行排序。讓我們建立一個NSComparator幫助我們(沒有這實際上是進行測試,但它應該編譯):

NSComparator comparatorForOriginalList(NSArray *list, NSString *key) { 
    NSArray *order = [list valueForKey:key]; // The personIds in the order we want 
    return ^(id obj1, id obj2) { 
    // We're passed personIds, map them to their locations 
    NSUInteger idx1 = [order indexOfObject:obj1]; 
    NSUInteger idx2 = [order indexOfObject:obj2]; 

    // And do the surprisingly tedious task of comparing them (why is this still so hard?) 
    if (idx1 > idx2) { 
     return (NSComparisonResult)NSOrderedDescending; 
    } 
    if (idx1 < idx2) { 
     return (NSComparisonResult)NSOrderedAscending; 
    } 
    return (NSComparisonResult)NSOrderedSame; 
    }; 
} 

給定一個列表和關鍵,它返回第一個對象的值的位置,其比較功能鍵入列表中的第二個對象,並告訴您它們是否按順序排列。

有了到位,創造了排序描述很簡單:

NSString *key = @"personId"; 
NSComparator comparator = comparatorForOriginalList(originalList, key); 
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:key 
              ascending:YES 
              comparator:comparator]; 
+0

這很好,沒想到:) – Cornelius

+0

我不認爲我可以使用這種比較核心數據,當我嘗試我得到異常:「不支持NSSortDescriptor(比較塊不支持)」 – Eyal

+0

我也嘗試在取回之後在內存中進行分類,但它需要大量時間,大約3分鐘左右才能處理〜4000個對象。 – Eyal