2011-01-12 106 views
1

我需要排序词典的NSDictionary。它看起来像:排序问题NSDictionary

{//dictionary 
     RU = "110.1"; //key and value 
     SG = "150.2"; //key and value 
     US = "50.3"; //key and value 
    } 

结果必须是这样的:

{//dictionary 
      SG = "150.2"; //key and value 
      RU = "110.1"; //key and value 
      US = "50.3"; //key and value 
     } 

我想这一点:

@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 

这就是NSLog的结果: 1)

{ 
SG, 
RU, 
US 
} 

2)

{ 
150.2, 
110.1, 
50.3 
} 

3)

{ 
      RU = "110.1"; 
      SG = "150.2"; 
      US = "50.3"; 
     } 

这究竟是为什么?你能帮我解决这个问题吗?

回答

1

一个NSDictionary没有经过修饰,所以它没有关系你按照什么顺序构造一个NSDIctionary。

NSArray被加工。如果你想让NSDictionary在内存中加密,你应该以某种方式创建一个NSArray的键值对。您也可以使用相应的元素返回两个NSArrays。

如果你只想遍历元素的方式,你可以迭代一个有序键值数组(这是koregan建议的)。

+0

ok。谢谢,伙计们。 –

5

NSDictionary是未分类的性质。由allKeysallValues检索的对象的顺序将始终未确定。即使您对订单进行逆向工程,它在下次系统更新时仍会发生变化。

然而有更强大的替代allKeys其用于检索在限定的和预测的顺序的键:

  • keysSortedByValueUsingSelector: - 有用用于根据所述值的对象的compare:方法以升序排序。
  • keysSortedByValueUsingComparator: - iOS 4的新功能,使用块进行内联排序。
2

WOW。 Thanx,PeyloW!这是我需要的!我也发现这个代码,它可以帮助我重新排序结果:

@implementation NSString (numericComparison) 

- (NSComparisonResult) floatCompare:(NSString *) other 
{ 
    float myValue = [self floatValue]; 
    float otherValue = [other floatValue]; 
    if (myValue == otherValue) return NSOrderedSame; 
    return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending); 
} 

- (NSComparisonResult) intCompare:(NSString *) other 
{ 
    int myValue = [self intValue]; 
    int otherValue = [other intValue]; 
    if (myValue == otherValue) return NSOrderedSame; 
    return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending); 
} 

@end 
+3

我的荣幸。不要忘记接受你认为正确的答案。帮助其他用户搜索答案,并为我的自我:)。 – PeyloW