我有一个NSArray
包含一些NSString
对象的。例如:
NSArray *objects = @[@"Stin",@"Foo",@"Ray",@"Space"];
现在我需要根据以下字符串顺序对这个数组进行排序。
NSArray *sortOrder = @[@"John",@"Foo",@"Space",@"Star",@"Ray",@"Stin"];
所以答案应该是
NSArray *sorted = @[@"Foo",@"Space",@"Ray",@"Stin"];
我怎样才能做到这一点?
答案: 根据 dasblinkenlight 的已接受答案,我做了以下工作,并且效果很好。
NSMutableArray *objects = @[@"Star",@"Stin",@"Foo",@"Ray",@"Space",@"John"];
NSArray *sortOrder = @[@"John",@"Foo",@"Space",@"Star",@"Ray",@"Stin"];
[objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int index1 = [sortOrder indexOfObject:obj1];
int index2 = [sortOrder indexOfObject:obj2];
if (index1 > index2)
return NSOrderedDescending;
if (index1 < index2)
return NSOrderedAscending;
return NSOrderedSame;
}];