【发布时间】:2016-02-29 15:28:41
【问题描述】:
我想做一种奇怪的字典排序。我有非唯一的值和键并得到类似的东西
NSArray *counts = [@"1",@"2",@"2",@"3",@"6",@"10"];
NSArray *names =[@"Jerry",@"Marge",@"Jerry",@"Marge",@"Jen",@"Mark"];
我想要的输出是一个具有唯一名称的降序列表。我不希望输出数组中同一个人的值较低。输出应该是。
sortedNames=[@"Mark",@"Jen",@"Marge",@"Jerry"]
sortedCounts=[@"10",@"6",@"3",@"2"];
我非常感谢您对此的帮助。
NSMutableArray *userNameArray = [[NSMutableArray alloc] init];
NSMutableArray *countArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in bigDick) {
NSString *nameString =[dict objectForKey:@"Name"];
NSString *countString =[dict objectForKey:@"Count"];
NSInteger countInt = [countString integerValue];
NSNumber *countNumber =[NSNumber numberWithInt:countInt];
[userNameArray addObject:nameString];
[countArray addObject:countNumber];
}
NSArray *namesAscending =[[userNameArray reverseObjectEnumerator]allObjects];
NSArray *countsAscending=[[countArray reverseObjectEnumerator]allObjects];
// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:countsAscending forKeys:namesAscending];
// Sort the first array
NSArray *sortedCountArray = [[dictionary allValues] sortedArrayUsingSelector:@selector(compare:)];
// Sort the second array based on the sorted first array
// NSArray *sortedNameArray= [dictionary objectsForKeys:sortedCountArray notFoundMarker:[NSNull null]];
NSMutableArray *nameArray =[[NSMutableArray alloc] init];
for (int i=1; i<sortedCountArray.count; i++) {
NSString *name = [dictionary allKeysForObject:sortedCountArray[i]];
if (sortedCountArray[i]!=sortedCountArray[i-1]) {
[nameArray addObject:name];
}
}
【问题讨论】:
-
为什么是字典?为什么不是自定义对象数组?你写过滤器了吗?这个问题太笼统了……
-
先排序,然后删除重复项。
-
你有没有尝试过?如果是这样,您遇到了什么问题?
标签: ios objective-c sorting nsarray nsdictionary