0

我有一组自定义对象。这些对象表示二进制文件中的段。该属性loc保存对象在文件中自己的位置,其中prev保存“上一个”对象的位置。在这种情况下,“上一个”和“下一个”并不一定意味着对象在文件中相继出现。第一个对象有prev = 0。最后一个对象没有以下对象将其位置保持为prev

我如何实现这种排序?对象的数量最初是未知的。

//My custom object
@interface MyObject : NSObject

@property (nonatomic, assign) NSInteger loc, prev;

@end

//In the implementation of some other class
NSMutableArray *array = [NSMutableArray new];

{// order should be 6
    MyObject *obj = [MyObject new];
    obj.loc = 3000;
    obj.prev = 111;
    [array addObject:obj];
}
{// order should be 2
    MyObject *obj = [MyObject new];
    obj.loc = 2000;
    obj.prev = 222;
    [array addObject:obj];
}
{// order should be 4
    MyObject *obj = [MyObject new];
    obj.loc = 333;
    obj.prev = 4000;
    [array addObject:obj];
}
{//  order should be 1
    MyObject *obj = [MyObject new];
    obj.loc = 222;
    obj.prev = 5000;
    [array addObject:obj];
}
{//  order should be 5
    MyObject *obj = [MyObject new];
    obj.loc = 111;
    obj.prev = 333;
    [array addObject:obj];
}
{// order should be 3
    MyObject *obj = [MyObject new];
    obj.loc = 4000;
    obj.prev = 2000;
    [array addObject:obj];
}
{// order should be 0
    MyObject *obj = [MyObject new];
    obj.loc = 5000;
    obj.prev = 0;
    [array addObject:obj];
}
4

2 回答 2

1

Try using lexicographical sorting:

NSArray *sorted = [array sortedArayUsingComparator:^(id obj1, id obj2) {
    if ([obj1 parentID] < [obj2 parentID] {
        return NSOrderedAscending;
    } else if ([obj1 parentID] > [obj2 parentID] {
        return NSOrderedDescending;
    } else if ([obj1 ID] < [obj2 ID] {
        return NSOrderedAscending;
    } else if ([obj1 ID] > [obj2 ID] {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }
}];
于 2013-02-04T11:57:04.783 回答
-1

没关系,我明白了。

NSMutableArray *unordered = [[NSMutableArray alloc] initWithArray:array];
NSMutableArray *ordered = [NSMutableArray new];

for(MyObject *myObj in array)
{
    if(!myObj.prev)
    {
        [orderedTables addObject:myObj];
        [unorderedTables removeObject:myObj];
        break;
    }
}

int counter = 0;
while(unordered.count && counter < ordered.count)
{
    MyObject *obj1 = [ordered objectAtIndex:counter++];

    for(int i = 0; i < unordered.count; ++i)
    {
        MyObj *obj2 = [unordered objectAtIndex:i];

        if(obj2.prev == obj1.loc)
        {
            [ordered addObject:obj2];
            [unordered removeObject:obj2];
            break;
        }
    }
}
于 2013-02-05T18:37:49.010 回答