NSDictionary In NSArray NSSortDescriptor 排序
来源:互联网 发布:网络蜘蛛并行策略 编辑:程序博客网 时间:2024/05/16 10:42
在这里说明一点东西:NSSortDescriptor是一个专门用来排序的。它可以设定关键字(字典中的key),根据对应key的value来进行一个排序。其中,如果是对array数组进行排序,那么object为字典,并且key对应的value 一定得是string,如果对应的是对象obj,那么系统会报错。一般用到的地方有NSArray(object 为NSDictionary),core data过滤筛选。
- 根据字典中关键字,对字典进行排序
-
- 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];
-
-
-
-
-
- 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];