我希望按索引排序NSArray
。
我可以对数组值进行排序,如何按索引排序...
NSArray* arr = [[NSArray alloc] initWithObjects:@"First",@"Second",@"Third",@"Fifth",@"Last",nil];
结果应该是这样的
iOS中是否有可用的直接方法?
答案 0 :(得分:5)
如果您只想反转数组,可以采用一种优雅的方式来实现。
我在danielpunkass的this answer中找到了解决方案。
NSArray *reversedArray = [[originalArray reverseObjectEnumerator] allObjects];
答案 1 :(得分:0)
NSMutableArray *array = ...;
[array sortUsingComparator: ^(id obj1, id obj2) {
_NSComparisonResult result = [obj1 compare:obj2]; // [NSString compare:]
if (result == NSOrderedAscending)
return NSOrderedDescending;
if (result == NSOrderedDescending)
return NSOrderedAscending;
return NSOrderedSame;
}];
OR
NSMutableArray *array = ...;
[array sortUsingComparator: ^(id obj1, id obj2) {
_NSComparisonResult result = [obj1 compare:obj2]; // [NSString compare:]
return -result; // minus result
}];
See apple documents about NSArray -sortUsingComparator:
NSObjCRuntime.h
enum _NSComparisonResult {NSOrderedAscending = -1,NSOrderedSame,NSOrderedDescending};