OC方法之---NSSortDescriptor使用注意以及直接排序字符串数组

来源:互联网 发布:金字塔双轨制软件 编辑:程序博客网 时间:2024/06/05 21:22

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,对数组本身排序。

0 0