使用另一个NSMutableArray的自定义对象对NSMutableArray进行排序

时间:2013-04-11 08:32:49

标签: iphone ios objective-c sorting nsmutablearray

我有2 NSMutableArrays。第一个数组包含具有属性NSString *itemID的自定义对象插件,第二个数组仅包含具有相同值NSString的{​​{1}}个对象,但是在另一个顺序中。我需要按每个对象的itemID属性排序第一个数组,它应该像第二个数组一样排序。

我怎么能这样做?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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]];
    }

编辑: 使用inplace类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]]];
    }];

答案 2 :(得分: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];
 }

享受编程!