NSArray排序

方法一:在数组的对象里增加比较方法,例如Person类型的数组,想按生日来排序,那么首先在Person类里增加下面的方法,注意返回值的类型。

- (NSComparisonResult)compare:(Person *)otherObject

{

return [self.birthDate compare:otherObject.birthDate];

}

当需要对这个数组进行排序时,写下面的代码:

NSArray *sortedArray;

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

方法二:NSSortDescriptor (较好)

首先定义一个比较器,规定按birthDate字段来排序

NSSortDescriptor *sortDescriptor;

sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES] autorelease];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *sortedArray;

sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

方法三:Blocks (最好)

10.6以后,可以使用代码段的方法。

NSArray *sortedArray;

sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b)

{ NSDate *first = [(Person*)a birthDate];

NSDate *second = [(Person*)b birthDate];

return [first compare:second];

}];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容