5

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

我怎么能做到这一点?

4

3 回答 3

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);
于 2013-04-11T08:48:53.527 回答
1

使用 as 键将自定义对象存储在字典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]]];
    }];
于 2013-04-11T08:41:50.203 回答
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];
 }

享受编程!

于 2013-04-11T08:42:42.977 回答