我正在开发计时器应用程序。我有一个数组。我想按升序对数组进行排序。假设我在数组中有 5 个元素,例如 10,100,50,30,70。
我想要像 10,30,50,70,100 这样的数组。
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];
编辑:如果元素是数字,则更改返回的类型以及 firstObject 和 secondObject 的类型。
来自苹果的文档
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;
}];
利用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;
}];
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);
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]]];
使用此代码:
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];
编辑:如果元素是数字,则更改返回的类型以及 firstObject 和 secondObject 的类型。