Sta*_*nko 1 sorting iphone nsdictionary
我需要对字典的NSDictionary进行排序.看起来像:
{//dictionary
RU = "110.1"; //key and value
SG = "150.2"; //key and value
US = "50.3"; //key and value
}
Run Code Online (Sandbox Code Playgroud)
结果需要像:
{//dictionary
SG = "150.2"; //key and value
RU = "110.1"; //key and value
US = "50.3"; //key and value
}
Run Code Online (Sandbox Code Playgroud)
我在尝试这个:
@implementation NSMutableDictionary (sorting)
-(NSMutableDictionary*)sortDictionary
{
NSArray *allKeys = [self allKeys];
NSMutableArray *allValues = [NSMutableArray array];
NSMutableArray *sortValues= [NSMutableArray array];
NSMutableArray *sortKeys= [NSMutableArray array];
for(int i=0;i<[[self allValues] count];i++)
{
[allValues addObject:[NSNumber numberWithFloat:[[[self allValues] objectAtIndex:i] floatValue]]];
}
[sortValues addObjectsFromArray:allValues];
[sortKeys addObjectsFromArray:[self allKeys]];
[sortValues sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"floatValue" ascending:NO] autorelease]]];
for(int i=0;i<[sortValues count];i++)
{
[sortKeys replaceObjectAtIndex:i withObject:[allKeys objectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]]]];
[allValues replaceObjectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]] withObject:[NSNull null]];
}
NSLog(@"%@", sortKeys);
NSLog(@"%@", sortValues);
NSLog(@"%@", [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]);
return [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys];
}
@end
Run Code Online (Sandbox Code Playgroud)
这是NSLog的结果:1)
{
SG,
RU,
US
}
Run Code Online (Sandbox Code Playgroud)
2)
{
150.2,
110.1,
50.3
}
Run Code Online (Sandbox Code Playgroud)
3)
{
RU = "110.1";
SG = "150.2";
US = "50.3";
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?你能帮我解决这个问题吗?
NSDictionary本质上没有分类.通过检索对象的顺序allKeys,并allValues会一直未定.即使您对订单进行逆向工程,它仍可能在下一次系统更新中发生变化.
然而,有更强大的替代品allKeys用于以定义和可预测的顺序检索密钥:
keysSortedByValueUsingSelector:- 可用于根据compare:值对象的方法按升序排序.keysSortedByValueUsingComparator: - iOS 4中的新功能,使用块进行内联排序.