Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 如何使用compare:options对NSArray排序_Iphone_Sorting_Compare_Nsarray - Fatal编程技术网

Iphone 如何使用compare:options对NSArray排序

Iphone 如何使用compare:options对NSArray排序,iphone,sorting,compare,nsarray,Iphone,Sorting,Compare,Nsarray,我有一个NSArray,其中包含作为NSString对象的数字。即 [array addObject:[NSString stringWithFormat:@"%d", 100]]; 如何对数组进行数字排序?我是否可以使用compare:options并将NSNumericSearch指定为NSStringCompareOptions?请给我一个示例/示例代码。因为您的对象是数字,而不是使用NSString对象,所以您可以使用NSNumber对象(通过stringValue属性轻松转换为字符串

我有一个NSArray,其中包含作为NSString对象的数字。即

[array addObject:[NSString stringWithFormat:@"%d", 100]];

如何对数组进行数字排序?我是否可以使用
compare:options
并将
NSNumericSearch
指定为
NSStringCompareOptions
?请给我一个示例/示例代码。

因为您的对象是数字,而不是使用NSString对象,所以您可以使用NSNumber对象(通过stringValue属性轻松转换为字符串)并使用

例如:

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:sorters];
[sorters release];

您可以使用为该方法提供的示例代码,该代码也适用于nsstring,因为它们还有
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];
//将此函数放在@implementation上方的某个位置
静态NSInteger intSort(id num1、id num2、void*context)
{
int v1=[num1 intValue];
int v2=[num2 intValue];
如果(v1v2)
退而求其次;
其他的
返回指定名称;
}
//像这样使用
NSArray*Darray;
SorterDarray=[anArray SorterDarrayUsingFunction:intSort上下文:NULL];

+1您可以使用以下行替换intSort的正文:return[(NSString*)num1比较:num2选项:NSNumericSearch]@gerry3当然,我刚刚从apple.com上获取了示例代码,看起来它可以完成这项工作