关于iphone:使用另一个NSMutableArray对自定义对象排序NSMutableArray

Sort NSMutableArray with custom objects by another NSMutableArray

本问题已经有最佳答案,请猛点这里访问。

我有2辆车。第一个数组包含具有NSString *itemID属性的自定义对象入口,第二个数组仅包含来自NSString对象的值与itemID相同,但顺序不同。我需要按每个对象的itemID属性对第一个数组进行排序,它应该像第二个数组一样进行排序。

我该怎么做?


1
2
3
4
5
6
7
8
9
10
11
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
2
3
4
[items sortUsingComparator:^NSComparisonResult(Attribute *obj1, Attribute *obj2)
{
    return [[NSNumber numberWithInt:[stringOrder indexOfObject:obj1.itemID]] compare:[NSNumber numberWithInt:[stringOrder indexOfObject:obj2.itemID]]]
}];

或者您可以使用以下代码段:

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

喜欢编程!


将自定义对象存储在以itemID为键的字典中,使用此字典作为查找来对对象排序:

1
2
3
4
5
6
7
8
9
10
11
12
    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的解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
    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]]];
    }];