【发布时间】:2016-03-11 07:13:26
【问题描述】:
我将 NSDictionary 作为参数传递给我的函数。我希望它的键和值在我插入时按顺序排列。 例如。预期输出是:
mutable dict:{
zKey1 = Value1;
fKey2 = Value2;
aKey3 = Value3;
}
我尝试了以下方法来为键创建和设置值。
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];
[mutableDict setObject:@"Value1" forKey:@"zKey1"];
[mutableDict setObject:@"Value2" forKey:@"fKey2"];
[mutableDict setObject:@"Value3" forKey:@"aKey3"];
NSMutableDictionary *dic2=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"1004",@"userId",@"cucumber",@"domain",@"168d5c02f ",@"token",@"1004",@"userId1",@"cucumber",@"domain1",@"168d5c02f ",@"token1", nil];
NSDictionary * dict = [NSDictionary
dictionaryWithObjects:@[@"Ravi",@"33",@"India",@"India"]
forKeys:@[@"name",@"age",@"location",@"country"]];
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys) {
[sortedValues addObject: [dict objectForKey: key]];
}
NSString *obj1=@"1004";
NSString *obj2=@"cucumber";
NSString *obj3=@"168d5c02f";
NSString *key1=@" userId";
NSString *key2=@"domain";
NSString *key3=@"token";
NSLog(@"dict %@",dict);
NSDictionary *dict8 =[NSDictionary
dictionaryWithObjects:@[obj1,obj2,obj3]
forKeys:@[key1,key2,key3]];
但没有任何效果我总是得到输出
mutable dict:{
aKey3 = Value3;
fKey2 = Value2;
zKey1 = Value1;
}
dict8 {
domain = cucumber;
token = 168d5c02f;
userId = 1004;
}
dict {
age = 33;
country = India;
location = India;
name = Ravi;
}
dic= {
domain = cucumber;
domain1 = cucumber;
token = "168d5c02f ";
token1 = "168d5c02f ";
userId = 1004;
userId1 = 1004;
}
它总是根据键的字母顺序对值进行排序。很多人说 NSDictionary 是一个未排序的容器。但它确实得到了排序。迫切需要帮助。提前谢谢你。
【问题讨论】:
-
NSDictionary默认不排序。它将永远没有任何顺序。要创建有序字典,您需要覆盖数据结构的现有形式。你可以阅读This tutorial来达到你的目的。 -
不,即使您按顺序添加它们,它也不是“按键排序”的 NSDictionary。如果输出是按顺序的,那只是你走运了。您可以通过排序键 NSArray 枚举具有所需顺序的键来打印它们,但不能直接使用 NSDictionary 本身。
-
为什么不使用 NSMutableArray ?语法也很简单..
@[@{"key1":value1},@{"key2":value2},@{"key3":value3}] -
但是我没有按顺序得到输出。它始终根据键按字母顺序排序。如图所示。
标签: ios objective-c iphone nsdictionary