您的位置:首页 > 其它

使用NSSortDescriptor对字符串数组进行排序

2014-12-04 22:47 387 查看
NSSortDescriptor 指定用于对象数组排序的对象的属性。

如果是Employee对象需要按照name来排序,就生成下面的descriptor

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:name ascending:YES];

如果需要多个排序,比如先按name排序,再按入职日期排序。那就创建两个descriptor

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:hireDate ascending:YES];

两个descriptor放到数组里一起传给需要排序的数组。

如果对象就是NSString,就是字符串数组排序,那更简单了,sortdescriptor的key直接指定为nil,就直接排序对象,而不是对象的某一个属性了。

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];

NSArray *descriptors = [NSArray arrayWithObject:descriptor];

NSArray *myDataArray = [NSArray arrayWithObjects:@"what", @"xero", @"highligth", @"mountain",@"Victory", @"Balance", nil];

NSArray *resultArray = [myDataArray sortedArrayUsingDescriptors:descriptors];

NSLog(@"%@", resultArray);

NSArray 使用sortedArrayUsingDescriptors,返回排序好的数组。

NSMutableArray可以直接使用sortUsingDescriptors,对数组本身排序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐