用另一个NSMutableArray将自定义对象排序为NSMutableArray

这个问题在这里已经有了答案:

  • 我如何排序一个NSMutableArray中的自定义对象? 25个答案
  • 并排排列两个NSArrays 4个答案

  • 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);
    

    将自定义对象存储在以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]]];
        }];
    

    您可以使用以下语法比较两个对象: -

    [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];
     }
    

    享受编程!

    链接地址: http://www.djcxy.com/p/70815.html

    上一篇: Sort NSMutableArray with custom objects by another NSMutableArray

    下一篇: how to sort nsmutablearray in ascending order with time comparison