0

我正在开发计时器应用程序。我有一个数组。我想按升序对数组进行排序。假设我在数组中有 5 个元素,例如 10,100,50,30,70。

我想要像 10,30,50,70,100 这样的数组。

4

6 回答 6

11
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];

编辑:如果元素是数字,则更改返回的类型以及 firstObject 和 secondObject 的类型。

于 2012-08-08T12:19:03.153 回答
3

来自苹果的文档

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
于 2012-08-08T12:19:46.097 回答
2

利用sortedArrayUsingComparator

NSArray *arr = @[@3, @2, @6, @1];
NSArray *sorted = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
    else return NSOrderedDescending;
}];
于 2012-08-08T12:20:12.270 回答
0
 NSArray * arr=[[NSArray alloc]initWithObjects:[NSNumber   numberWithInt:10],[NSNumber   numberWithInt:100],[NSNumber   numberWithInt:50],[NSNumber   numberWithInt:30],[NSNumber   numberWithInt:70], nil];
    NSLog(@"Before sorting%@",arr);

    arr = [arr sortedArrayUsingSelector:@selector(compare:)];
      NSLog(@"After sorting%@",arr);
于 2012-08-08T12:42:43.390 回答
-2
NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {

    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];
于 2012-08-08T12:19:21.780 回答
-2

使用此代码:

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];

编辑:如果元素是数字,则更改返回的类型以及 firstObject 和 secondObject 的类型。

于 2012-08-08T12:27:11.340 回答