我正在寻找一个数组(mainArray),包含几个数组(array1,2,3,...)
比较器(NSnumber)位于每个array1,2,3中的index8 ...
我应该使用哪种方法?
你有什么解决办法吗?
非常感谢
干杯
蒂姆
我正在寻找一个数组(mainArray),包含几个数组(array1,2,3,...)
比较器(NSnumber)位于每个array1,2,3中的index8 ...
我应该使用哪种方法?
你有什么解决办法吗?
非常感谢
干杯
蒂姆
您可以对NSMutableArray
.
// Create an array of arrays of integers using the new array and number literal syntax
NSMutableArray* arrayOfArrays =
[NSMutableArray arrayWithArray:@[ @[ @0, @1, @2 ], @[ @1, @2, @3 ] ];
// The key on which to sort is located at this index in each array
NSUInteger sortKeyIndex = 2;
// Sort the array of arrays using a stable sort. This means that arrays which considered
// equal in arrayOfArrays will retain their relative positions in the sorted arrayOfArrays
// Use a comparator block to sort arrayOfArrays.
[arrayOfArrays sortWithOptions:NSSortStable
usingComparator:^(id lhs, id rhs) {
// Cast the two elements of arrayOfArrays being compared to their actual type (NSArray)
NSArray* lhsArray = lhs;
NSArray* rhsArray = rhs;
// Extract the element of each array which is used as a sort key
// This makes use of the new array index syntax
NSNumber* lhsNumber = lhsArray[sortKeyIndex];
NSNumber* rhsNumber = rhs[sortKeyIndex];
// Unbox the integers from each NSNumber to get the actual values of the sort keys
NSInteger lhsSortKey = [lhs integerValue];
NSInteger rhsSortKey = [rhs integerValue];
// Compare the two sort keys
if (lhsSortKey < rhsSortKey) {
return NSOrderedAscending;
} else if (lhsSortKey > rhsSortKey) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
如果使用比较器对 NSArray 进行排序,则可以完全控制每个比较。
所以你可以使用:
array=[array sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2)
{
// obj1 and obj2 are two arrays
NSNumber* n1=[obj1 objectAtIndex:8];
NSNumber* n2=[obj2 objectAtIndex: 8];
<compare the numbers and return NSOrderedAscending, NSOrderedSame or NSOrderedDescending>
}];