根据NSMutablearray中的内容对NSMutableDictionary进行排序

时间:2011-09-08 09:51:42

标签: objective-c cocoa

我有一个数组NSMutableArray,其值为 10,2,13,4。

还有NSMutableDictionary值 (10,a),(20,b),(13,c),(2,d),(33,e)

我想在NSMutableDictionary中对dict的结果进行排序,dict的结果应该是(10,a),(2,d),(13,c)

2 个答案:

答案 0 :(得分:1)

我为你写的功能。希望,它会帮助你:

- (void)removeUnnedful
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                          @"a", [NSNumber numberWithInt:10],  
                          @"b", [NSNumber numberWithInt:20], 
                          @"c", [NSNumber numberWithInt:13], 
                          @"d", [NSNumber numberWithInt:2 ],
                          @"e", [NSNumber numberWithInt:33],  
                          nil];
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                             [NSNumber numberWithInt:10],
                             [NSNumber numberWithInt:2 ],
                             [NSNumber numberWithInt:13],
                             [NSNumber numberWithInt:14], nil];

    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    for (NSNumber *key in [dict allKeys])
    {
        NSLog(@"%@", key);
        if ([array containsObject:key])
        {
            [newDict setObject:[dict objectForKey:key] forKey:key];
        }
    }

    for (NSNumber *key in [newDict allKeys])
        NSLog(@"key: %@, value: %@", key, [newDict objectForKey:key]);

    [dict release];
    [array release];
}

答案 1 :(得分:1)

未定义NSDictionary实例中的键和值的排序顺序。 (见[NSDictionary allKeys]
由于您已经有一系列有序键,您可以简单地迭代它并访问该键的字典值:

NSMutableArray* sortedArray = [NSMutableArray arrayWithObjects:@"10", @"2", @"13", @"4", nil];
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"a", @"10", @"b", @"20", @"c", @"13", @"d", @"2", @"e", @"33" , nil];
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
for(id key in sortedArray)
{
    id value = [dictionary objectForKey:key];
    if(value != nil)
    {
        [filteredDictionary setObject:[dictionary objectForKey:key] forKey:key];
    }
}
NSLog(@"%@", filteredDictionary);

请注意,[NSDictionary description]的默认实现对每个键的输出升序排序(对于NSString类型的键),但这只是一种表示 - NSDictionaries没有已定义的排序顺序,所以您不应该依赖allKeysallValues

的排序