开发者

Sort NSMutableDictionary based on contents in NSMutable array

I have a array NSMutableArray with Values say 10, 2, 13, 4.

Also there is NSMutableDictionary with values say (10, a), (20, b), (13, c), (2, d), (33, e)

I want to sort values in NSMutableDictionary in a way that result of dict should be (10, a), (2, d)开发者_如何学编程, (13, c)


I wrote for you function. Hope, it will help you:

- (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];
}


Sort order of keys and values in an instance of NSDictionary is not defined. (see [NSDictionary allKeys])
As you already have an array of ordered keys, you can simply iterate over that and access the dictionary value for that key:

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);

Note that the default implementation of [NSDictionary description] sorts the output ascending per key (for keys of type NSString), but this is just a representation - NSDictionaries have no defined sort order so you shouldn't rely on the sorting of allKeys and allValues

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜