有一個未分組的NSMutableDictionary
{
A= "3";
B= "2";
C= "4";
}
我想要的結果是這樣:
{
B= "2";
A= "3";
C= "4";
}
如何在objectivec中獲得結果?
多謝~
你不能通過值進行NSMutableDictionary 分組。如果改變NSArray的關鍵字和賦值的話,可以。代碼如下:
NSMutableDictionary *results;
NSArray *sortedKeys = [results keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue])
return (NSComparisonResult)NSOrderedDescending;
if ([obj1 integerValue] < [obj2 integerValue])
return (NSComparisonResult)NSOrderedAscending;
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortedValues = [[results allValues] sortedArrayUsingSelector:@selector(compare:)];
for (int s = ([sortedValues count]-1); s >= 0; s--) {
NSLog(@" %@ = %@",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]);
}
for (int s = 0; s < [sortedValues count]; s++) {
NSLog(@" %@ = %@",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]);
}