我有一个阵列NSMutableArray
与值说 10,2,13,4排序的NSMutableDictionary基于在NSMutable阵列内容
也有是NSMutableDictionary
与值说 (10,A),(20,B ),(13,c),(2,d),(33,e)
我想排序NSMutableDictionary
中的值,使字典结果为(10,a),(2,d) ,(13,c)
我有一个阵列NSMutableArray
与值说 10,2,13,4排序的NSMutableDictionary基于在NSMutable阵列内容
也有是NSMutableDictionary
与值说 (10,A),(20,B ),(13,c),(2,d),(33,e)
我想排序NSMutableDictionary
中的值,使字典结果为(10,a),(2,d) ,(13,c)
我为你写的函数。希望它能帮助你:
- (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];
}
没有定义在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
没有定义的排序顺序,所以你不应该依靠allKeys
排序和allValues
你刚刚重复我的答案.... – Nekto
你想删除不在阵的值字典? – Nekto
是的。你是对的。 – MacGeek
查看我的答案,希望能帮到你。 – Nekto