|
NSSortDescriptor 指定用于對象數(shù)組排序的對象的屬性。
如果是Employee對象需要按照name來排序,就生成下面的descriptor
NSSortDescriptor *descriptor =
[NSSortDescriptor sortDescriptorWithKey:name ascending:YES];
如果需要多個排序,比如先按name排序,再按入職日期排序。那就創(chuàng)建兩個descriptor
NSSortDescriptor *descriptor =
[NSSortDescriptor sortDescriptorWithKey:hireDate ascending:YES];
兩個descriptor放到數(shù)組里一起傳給需要排序的數(shù)組。
如果對象就是NSString,就是字符串數(shù)組排序,那更簡單了,sortdescriptor的key直接指定為nil,就直接排序?qū)ο?,而不是對象的某一個屬性了。
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,返回排序好的數(shù)組。
NSMutableArray可以直接使用sortUsingDescriptors,對數(shù)組本身排序。
|