NSDictionary In NSArray NSSortDescriptor 排序 iOS

转载说明:(谢谢)

http://blog.csdn.net/a21064346/article/details/7762034

点击打开链接

在这里说明一点东西:
NSSortDescriptor是一个专门用来排序的。它可以设定关键字(字典中的key),根据对应key的value来进行一个排序。
其中,如果是对array数组进行排序,那么object为字典,并且key对应的value 一定得是string,如果对应的是对象obj,那么系统会报错。
一般用到的地方有NSArray(object 为NSDictionary),core data过滤筛选。

根据字典中关键字,对字典进行排序  
//First create the array of dictionaries  
NSString *LAST = @"lastName";  
NSString *FIRST = @"firstName";  
   
NSMutableArray *array = [NSMutableArray array];  
NSArray *sortedArray;  
   
NSDictionary *dict;  
dict = [NSDictionary dictionaryWithObjectsAndKeys:  
                     @"Jo", FIRST, @"Smith", LAST, nil];  
[array addObject:dict];  
   
dict = [NSDictionary dictionaryWithObjectsAndKeys:  
                     @"Joe", FIRST, @"Smith", LAST, nil];  
[array addObject:dict];  
   
dict = [NSDictionary dictionaryWithObjectsAndKeys:  
                     @"Joe", FIRST, @"Smythe", LAST, nil];  
[array addObject:dict];  
   
dict = [NSDictionary dictionaryWithObjectsAndKeys:  
                     @"Joanne", FIRST, @"Smith", LAST, nil];  
[array addObject:dict];  
   
dict = [NSDictionary dictionaryWithObjectsAndKeys:  
                     @"Robert", FIRST, @"Jones", LAST, nil];  
[array addObject:dict];  
   
//Next we sort the contents of the array by last name then first name  
   
// The results are likely to be shown to a user  
// Note the use of the localizedCaseInsensitiveCompare: selector  
NSSortDescriptor *lastDescriptor =  
    [[[NSSortDescriptor alloc] initWithKey:LAST  
                               ascending:YES  
                               selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];  
NSSortDescriptor *firstDescriptor =  
    [[[NSSortDescriptor alloc] initWithKey:FIRST  
                               ascending:YES  
                               selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];  
   
NSArray *descriptors = [NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil];  
sortedArray = [array sortedArrayUsingDescriptors:descriptors];










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值