Ios 字典键排序
嗨,我有一本字典,它是由我设置的,我正在访问它 代码如下Ios 字典键排序,ios,objective-c,nsmutabledictionary,Ios,Objective C,Nsmutabledictionary,嗨,我有一本字典,它是由我设置的,我正在访问它 代码如下 NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary]; [filteredDictionary setObject:@"xcode" forKey:@"1"]; [filteredDictionary setObject:@"ios" forKey:@"3"]; [filteredDictionary setObject
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
[filteredDictionary setObject:@"xcode" forKey:@"1"];
[filteredDictionary setObject:@"ios" forKey:@"3"];
[filteredDictionary setObject:@"ipad" forKey:@"2"];
[filteredDictionary setObject:@"iphone" forKey:@"5"];
[filteredDictionary setObject:@"simulator" forKey:@"4"];
NSLog(@"%@",filteredDictionary);
电流输出:
{
1 = xcode;
2 = ipad;
3 = ios;
4 = simulator;
5 = iphone;
}
but i want
{
1 = xcode;
3 = ios;
2 = ipad;
5 = iphone;
4 = simulator;
}
当我在字典中设置对象时,我想要它
我不想让这本词典按它分类
请帮忙
提前感谢….您无法对键进行适当排序,因为字典是哈希表 您可以将键/值对作为数组获取,并在显示之前对数组进行排序:
请参见当您访问时,Dictionary不保证订单。如果要保持元素的顺序,必须使用NSArray
很少有像OrderedDictionary()这样的想法,但是最好用正确的对象来达到正确的目的。 < P > NordBrand并不意味着对对象进行排序,而考虑元素的顺序是绝对不重要的。 NSDICTORIAL是一组键值对,期望使用相应的键访问值,因此
索引的概念在其中没有用处。
不过,如果你想在索引上玩游戏,你应该使用NSArray。NSDictionary不记得你添加键的顺序。你得自己做。我建议使用一种新的方法
显然,这是一个令人头疼的问题,所以请创建一个新的集合类
@implementation MyMutableOrderedDictionary
{
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
NSMutableOrderedSet* keyOrder = [[NSMutableOrderedSet alloc] init];
}
-(void) setObject: (id) object forKey: (id <NSCopying>) key
{
[filteredDictionary setObject: object forKey: key];
[keyOrder addObject: key];
}
-(NSOrderedSet*) keys
{
return keyOrder;
}
// Some other methods
@end
@实现MyMutableOrderedDictionary
{
NSMutableDictionary*filteredDictionary=[NSMutableDictionary];
NSMutableOrderedSet*keyOrder=[[NSMutableOrderedSet alloc]init];
}
-(void)setObject:(id)object forKey:(id)键
{
[FilterEditionary setObject:object-forKey:key];
[keyOrder addObject:key];
}
-(数据集*)键
{
返回键顺序;
}
//其他一些方法
@结束
您可以通过内部迭代keyOrder
或外部迭代keys
属性来实现一些枚举方法
请注意,我并没有将NSMutableDictionary子类化,因为它是一个类集群,所以这可能会让人头疼。这将对您有所帮助
@implementation MyMutableOrderedDictionary
{
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
NSMutableOrderedSet* keyOrder = [[NSMutableOrderedSet alloc] init];
}
-(void) setObject: (id) object forKey: (id <NSCopying>) key
{
[filteredDictionary setObject: object forKey: key];
[keyOrder addObject: key];
}
-(NSOrderedSet*) keys
{
return keyOrder;
}
// Some other methods
@end