对 NSMutable 数组进行升序排序

Sorting a NSMutable Array Ascending Order

这里有问题。

我有一个 NSMutableArray,其中有以下数字:

99,
161,
178,
179,
180,
181,
182,
184,
185,
194,
195,
196,
205,
206,
210,
218,
337,  <------- Here is the 337
227,
232,
240,
244,
346,
352,
353

如你所见,218和227之间有一个337,当下一个数字小于337时,如何让337继续前进?

或者换句话说,如何使我的 NSMutableArray 上升?

在没有代码可评估的情况下,您已经尝试过什么以及可能做错了什么不是很清楚。请检查 NSArray class 参考以尝试最适合您的问题的排序方法版本。还要记住数组应该包含对象,在你的例子中是 NSNumbers。那么你可以使用下面的方法:

sortedArrayUsingFunction:context: Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

Declaration SWIFT func sortedArrayUsingFunction(_ comparator: CFunctionPointer<((AnyObject!, AnyObject!, UnsafeMutablePointer) -> Int)>, context context: UnsafeMutablePointer) -> [AnyObject] OBJECTIVE-C - (NSArray )sortedArrayUsingFunction:(NSInteger ()(id, id, void *))comparator context:(void *)context Discussion The new array contains references to the receiving array’s elements, not copies of them.

The comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.

Given anArray (an array of NSNumber objects) and a comparison function of this type:

NSInteger intSort(id num1, id num2, void *context) { int v1 = [num1 intValue]; int v2 = [num2 intValue]; if (v1 < v2) return NSOrderedAscending; else if (v1 > v2) return NSOrderedDescending; else return NSOrderedSame; } A sorted version of anArray is created in this way:

NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL]; Import Statement import Foundation

Availability Available in iOS 2.0 and later.

您可以试试:

NSArray *arrayOfNumbers = @[@(4), @(2), @(13), @(156), @(1), @(-2)];
NSSortDescriptor *lowestToHighest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
arrayOfNumbers = [arrayOfNumbers sortedArrayUsingDescriptors:@[lowestToHighest]];

执行此操作,但首先要确保您的数组是 NSNumbers,而不仅仅是普通的 int:

[arrayOfNumbers sortedArrayUsingSelector:@selector(compare:)];