我有一系列自定义对象。对象表示二进制文件中的段。
属性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];
}
答案 0 :(得分:1)
尝试使用词典排序:
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;
}
}];
答案 1 :(得分:-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;
}
}
}