手头上碰到一个项目,需要给数组中的字典中的一个字段排序,想了想,干脆再字典中增加一个字段,用来记录需要排序字段的第一个字符,用它来作为比较的对象,进行排序。
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *arr = @[@{@"sortKey":@"54"},@{@"sortKey":@"67"},@{@"sortKey":@"78"},@{@"sortKey":@"87"},@{@"sortKey":@"32"},@{@"sortKey":@"43"},@{@"sortKey":@""},@{@"sortKey":@"f"},@{@"sortKey":@"12"},@{@"sortKey":@"43"},@{@"sortKey":@"56"},@{@"sortKey":@"567"},@{@"sortKey":@"435"}];
NSArray *sarr = [arr sortedArrayUsingFunction:compare context:NULL];
NSLog(@"sarr:%@",sarr);
}
NSComparisonResult compare(NSDictionary *firstDict, NSDictionary *secondDict, void *context) {
if ([[firstDict objectForKey:@"sortKey"] intValue] < [[secondDict objectForKey:@"sortKey"] intValue])
return NSOrderedAscending;
else if ([[firstDict objectForKey:@"sortKey"] intValue] > [[secondDict objectForKey:@"sortKey"] intValue])
return NSOrderedDescending;
else
return NSOrderedSame;
}