本帖最后由 fantacyleo 于 2014-7-21 13:33 编辑
如果你要按多个property进行排序,descriptor就很方便了。比如按Person的名字排序,相同名字再按年龄排序:
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- @property (nonatomic, strong) NSString *name;
- @property (nonatomic, assign) int age;
- @end
- @implementation Person
- - (id)initWithName:(NSString *)name andAge:(int)age
- {
- self = [super init];
- if (self) {
- _name = name;
- _age = age;
- }
- return self;
- }
- - (NSString *)description
- {
- return [NSString stringWithFormat:@"%@:%d", self.name, self.age];
- }
- @end
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
- Person *p1 = [[Person alloc] initWithName:@"Jack" andAge:20];
- Person *p2 = [[Person alloc] initWithName:@"John" andAge:21];
- Person *p3 = [[Person alloc] initWithName:@"Jack" andAge:18];
- NSArray *strArr = @[p1, p2, p3];
-
- NSSortDescriptor *sortName = [NSSortDescriptor
- sortDescriptorWithKey:@"name"
- ascending:YES];
-
- NSSortDescriptor *sortAge = [NSSortDescriptor
- sortDescriptorWithKey:@"age"
- ascending:YES];
- NSArray *sorted = [strArr sortedArrayUsingDescriptors:@[sortName, sortAge]];
- NSLog(@"%@", sorted);
-
- }
- return 0;
- }
复制代码 |