我有一个NSArray,其中包含一些NSString对象.例如:
NSArray *objects = @[@"Stin",@"Foo",@"Ray",@"Space"];
现在我需要根据字符串的顺序对此数组进行排序.
NSArray *sortOrder = @[@"John",@"Space",@"Star",@"Stin"];
所以答案应该是
NSArray *sorted = @[@"Foo",@"Stin"];
我怎样才能做到这一点?
回答:
根据dasblinkenlight的接受的答案,我做了以下,它有魅力.
NSMutableArray *objects = @[@"Star",@"Stin",@"John"]; NSArray *sortOrder = @[@"John",@"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; }];