如何使用compare:options对NSArray进行排序

avi*_*avi 6 sorting iphone compare nsarray

我有一个NSArray包含数字作为NSString对象.即.

[array addObject:[NSString stringWithFormat:@"%d", 100]];
Run Code Online (Sandbox Code Playgroud)

如何以数字方式对数组进行排序?我可以使用compare:options并指定NSNumericSearchNSStringCompareOptions吗?请给我一个示例/示例代码.

epa*_*tel 16

您可以使用为该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];
Run Code Online (Sandbox Code Playgroud)


ger*_*ry3 6

由于您的对象是数字,而不是使用NSString对象,您可以使用NSNumber对象(通过stringValue属性轻松转换为字符串)并使用sortedArrayUsingDescriptors对数组进行排序:.

例如:

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:sorters];
[sorters release];
Run Code Online (Sandbox Code Playgroud)