对数组里的数据进行排序

记录一些常用的排序api使用的方法:NSSortDescriptorNSComparator

1、[xxx sortedArrayUsingDescriptors:xx]

排序后返回一个新的不可变数组,NSArrayNSMutableArray都可以使用

// 数组里是简单的数字或字符串的排序
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *simpleList1 = @[@1,@3,@2,@5,@4];
NSMutableArray *simpleList1M = [@[@1,@3,@2,@5,@4] mutableCopy];
// 排完序后返回一个不可变数组
NSArray *simpleList1Sorted = [simpleList1 sortedArrayUsingDescriptors:@[sortDesc]];
NSArray *simpleList1MSorted = [simpleList1M sortedArrayUsingDescriptors:@[sortDesc]];

// 数据里是字典或其他model等复杂的排序
NSSortDescriptor *sortDesc2 = [[NSSortDescriptor alloc] initWithKey:@"sortCode" ascending:YES];
NSArray *complexList1 = @[@{@"name":@"aa",@"sortCode":@1},@{@"name":@"cc",@"sortCode":@3},@{@"name":@"bb",@"sortCode":@2}];
NSArray *complexList1Sorted = [complexList1 sortedArrayUsingDescriptors:@[sortDesc2]];

2、[xxx sortUsingDescriptors:xx]

对原数组进行排序,只有NSMutableArray可以使用

// 数组里是简单的数字或字符串的排序
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSMutableArray *simpleList1M = [@[@1,@3,@2,@5,@4] mutableCopy];
// 对原数组进行排序
[simpleList1M sortUsingDescriptors:@[sortDesc]];

// 数据里是字典或其他model等复杂的排序
NSSortDescriptor *sortDesc2 = [[NSSortDescriptor alloc] initWithKey:@"sortCode" ascending:YES];
NSMutableArray *complexList1M = [@[@{@"name":@"aa",@"sortCode":@1},@{@"name":@"cc",@"sortCode":@3},@{@"name":@"bb",@"sortCode":@2}] mutableCopy];
[complexList1M sortUsingDescriptors:@[sortDesc]];

你可能感兴趣的:(对数组里的数据进行排序)