//第一種,利用數(shù)組的sortedArrayUsingComparator調(diào)用 NSComparator 刹勃,obj1和obj2指的數(shù)組中的對象
NSComparator cmptr = ^(id obj1, id obj2){
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
//排序前
NSMutableString *outputBefore = [[NSMutableString alloc] init];
for(NSString *str in sortArray){
[outputBefore appendFormat:@"];
}
NSLog(@"排序前:%@",outputBefore);
//第一種排序
NSArray *array = [sortArray sortedArrayUsingComparator:cmptr];
NSMutableString *outputAfter = [[NSMutableString alloc] init];
for(NSString *str in array){
[outputAfter appendFormat:@"];
}
NSLog(@"排序后:%@",outputAfter);
第二種 排序方法 利用sortedArrayUsingFunction 調(diào)用 對應(yīng)方法customSort膘融,這個方法中的obj1和obj2分別是指數(shù)組中的對象。
NSInteger customSort(id obj1, id obj2,void* context){
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}
NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
//排序前
NSMutableString *outputBefore = [[NSMutableString alloc] init];
for(NSString *str in sortArray){
[outputBefore appendFormat:@"];
}
NSLog(@"排序前:%@",outputBefore);
NSArray *array = [sortArray sortedArrayUsingFunction:customSort context:nil];
NSMutableString *outputAfter = [[NSMutableString alloc] init];
for(NSString *str in array){
[outputAfter appendFormat:@"];
}
NSLog(@"排序后:%@",outputAfter);
第三種 利用sortUsingDescriptors調(diào)用NSSortDescriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:NO];//其中岖寞,price為數(shù)組中的對象的屬性纽帖,這個針對數(shù)組中存放對象比較更簡潔方便
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:1];
[_totalInfoArray sortUsingDescriptors:sortDescriptors];
[_airListView refreshTable:_totalInfoArray];
NSString *s1 = @"sdf";
NSArray *arr1 = @[@"1",@"2"];
NSDictionary *dict1 = @{@"1":@"a",@"2":@"b"};
NSMutableArray *arr2 = @[@"1",@"2"].mutableCopy;
NSMutableDictionary *dict2 = @{@"a":@"1",@"b":@"2"}.mutableCopy;
// 如果想使用字面量初始化數(shù)組或者字典闯狱,可以是使用.mutablecopy即可