您的位置:首页 > 移动开发 > IOS开发

0003-¥¥¥¥可变数组按条件排序sort NSMutableArray

2018-02-06 09:06 447 查看
How do I sort an NSMutableArray with custom objects in it?

三种方法

1.使用个方法

2.使用NSSortDescriptor

3.使用block

总结:方法2更好,可以指明是升序还是降序,使用的是KVC

方法1代码:

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}


方法2代码:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];


方法3代码:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];


原文链接

QQ群和微信群

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS