Sorting an NSArray by an NSDictionary value

余生长醉 提交于 2019-12-03 03:46:52

Although I question the use of strings here, the simplest way to work with that data with be:

[array sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
    NSString *age1 = [item1 objectForKey:@"age"];
    NSString *age2 = [item2 objectForKey:@"age"];
    return [age1 compare:age2 options:NSNumericSearch];
}];

Or, using Objective-C's more recent subscripting features:

[array sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
    return [item1[@"age"] compare:item2[@"age"] options:NSNumericSearch];
}];

Easiest would be storing the age as a number instead of a string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!