标签:
//如果想排序以后再取,可以这样:
NSSet *users = [groupUser users];
//如果是存的字典,则key后面写的是想按照哪个关键字进行排序
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd, nil];
NSArray *userArray = [users sortedArrayUsingDescriptors:sortDescriptors];
//如果直接取,可以这样:
NSArray *userArray = [users allObjects];
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,对数组本身排序。
关于NSSortDescriptor
NSMutableArray *ma1 = [[NSMutableArray alloc] init];
[ma1 addObject:@"2"];
[ma1 addObject:@"1"];
[ma1 addObject:@"3"];
NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
NSArray *arr1 = [ma1 sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
for (NSString *str in arr1) {
NSLog(@"%@", str);
}
NSMutableArray *ma2 = [[NSMutableArray alloc] init];
[ma2 addObject:@"b"];
[ma2 addObject:@"c"];
[ma2 addObject:@"a"];
NSSortDescriptor *sd2 = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
NSArray *arr2 = [ma2 sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd2, nil]];
for (NSString *str in arr2) {
NSLog(@"%@", str);
}
NSMutableArray *ma3 = [[NSMutableArray alloc] init];
NSMutableDictionary *md1 = [[NSMutableDictionary alloc] init];
[md1 setObject:@"e" forKey:@"name"];
NSMutableDictionary *md2 = [[NSMutableDictionary alloc] init];
[md2 setObject:@"d" forKey:@"name"];
NSMutableDictionary *md3 = [[NSMutableDictionary alloc] init];
[md3 setObject:@"f" forKey:@"name"];
[ma3 addObject:md1];
[ma3 addObject:md2];
[ma3 addObject:md3];
[md1 release];
[md2 release];
[md3 release];
NSSortDescriptor *sd3 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *arr3 = [ma3 sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd3, nil]];
for (NSMutableDictionary *md in arr3) {
NSLog(@"%@", [md objectForKey:@"name"]);
}
引用自:http://blog.sina.com.cn/s/blog_8c87ba3b0101phr5.html
http://www.cnblogs.com/zhw511006/archive/2011/06/16/2082787.html
http://blog.csdn.net/zhangkongzhongyun/article/details/7904055
NSSet转成NSArray 以及NSSortDescriptor的使用
标签:
原文地址:http://www.cnblogs.com/endtel/p/4845848.html