我有一个 NSArray,其中包含数字作为 NSString 对象。 IE。
[array addObject:[NSString stringWithFormat:@"%d", 100]];
如何对数组进行数字排序?我可以使用 compare:options
并将 NSNumericSearch
指定为 NSStringCompareOptions
吗?请给我一个示例/示例代码。
最佳答案
您可以使用 sortedArrayUsingFunction:context:
给出的示例代码方法也应该适用于 NSStrings,因为它们也有 intValue
方法。
// Place this functions somewhere above @implementation
static 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;
}
// And used like this
NSArray *sortedArray;
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];
关于iphone - 如何使用比较:options对NSArray进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2031990/