2013-04-11 217 views
5

我有2 NSMutableArrays。第一個數組包含具有屬性NSString *itemID的自定義對象實例,第二個數組僅包含NSString對象,其值爲itemID,但以其他順序排列。我需要按照每個對象的itemID屬性排序第一個數組,並且它應該像第二個數組一樣排序。用另一個NSMutableArray對自定義對象排序NSMutableArray

我該怎麼做?

+0

array is short,based on one key? – 2013-04-11 08:53:46

+0

http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it/805589#805589 – 2013-04-11 09:00:31

+0

我見過這個解決方案,它不適合我問題 – 2013-04-11 09:18:21

回答

3
guideArray = < YOUR SECOND ARRAY WITH STRING OBJECT >;  
unsortedArray = < YOUR FIRST ARRAY WITH CUSTOM OBJECT >; 

[unsortedArray sortUsingComparator:^(id o1, id o2) { 
    Items *item1 = o1; 
    Items *item2 = o2; 
    NSInteger idx1 = [guideArray indexOfObject:item1.ItemID]; 
    NSInteger idx2 = [guideArray indexOfObject:item2.ItemID]; 
    return idx1 - idx2; 
}]; 
NSLog(@"%@",unsortedArray); 
+0

非常感謝,就是這樣。 – 2013-04-11 08:56:57

+0

很棒的答案..... – 2013-04-11 09:06:29

1

存儲在字典中的自定義對象與itemID爲重點,用這個字典作爲查找的對象進行排序:

NSArray *objects; // your objects 
    NSMutableArray *hintArray; // your sorted IDs 
    NSMutableDictionary *lookupDict = [[NSMutableDictionary alloc] initWithCapacity:[objects count]]; 
    NSMutableArray *sortedObjects = [[NSMutableArray alloc] initWithCapacity:[hintArray count]]; 

    for (id object in objects) { 
     [lookupDict setValue:object forKey:[object itemID]]; 
    } 

    for (id hint in hintArray) { 
     [sortedObjects addObject:[lookupDict valueForKey:hint]]; 
    } 

編輯: 解決方案與就地排序objects

NSMutableArray *objects; 
    NSMutableArray *hintArray; 
    NSMutableDictionary *lookupDict = [[NSMutableDictionary alloc] initWithCapacity:[hintArray count]]; 

    int i = 0; 
    for (NSString *itemID in hintArray) { 
     [lookupDict setValue:[NSNumber numberWithInt:i] forKey:itemID]; 
     i++; 
    } 

    [objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
     return [[lookupDict valueForKey:[obj1 itemID]] compare:[lookupDict valueForKey:[obj2 itemID]]]; 
    }]; 
+0

NSDictionary不會添加到列表的末尾。所以它不會幫助 – 2013-04-11 08:47:07

+0

我沒有得到您的評論。我使用簡單的構建查找字典來避免搜索排序後的id列表中的每個項目,當您獲得大量項目時這將變得非常昂貴。 – 2013-04-11 08:51:23

1

您可以使用以下語法比較兩個對象: -

[items sortUsingComparator:^NSComparisonResult(Attribute *obj1, Attribute *obj2) 
{ 
    return [[NSNumber numberWithInt:[stringOrder indexOfObject:obj1.itemID]] compare:[NSNumber numberWithInt:[stringOrder indexOfObject:obj2.itemID]]] 
}]; 

否則,你可以使用下面的代碼片段:

NSArray* sortedKeys = [dict keysSortedByValueUsingComparator:^(id obj1, id obj2) 
{ 
    return [obj1 compareTo:obj2]; 
} 

欣賞節目!

+1

謝謝,這也是可行的答案 – 2013-04-11 08:57:16

相關問題