NSDictionary 总是显示 null
我在初始化 nsdictionary 并将其添加到数组时遇到问题。我尝试了两种方法,但都失败了。我的字典总是空的。
Appoach1:
NSMutableDictionary *Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1",@"State_Name",@"2",@"Name",@"3",@"Address",@"4",@"Ph", nil];// initialized in viewdidload
-(void)find:(NSInteger)Item{
switch (Item) {
case 0:
[Data setValue:string forKey:@"State_Name"];
break;
case 1:
[Data setValue:string forKey:@"Name"];
break;
case 2:
[Data setValue:string forKey:@"TAddress"];
break;
case 3:
[Data setValue:string forKey:@"Ph"];
break;
default:
break;
}
}
Approach2:
NSMutableDictionary *Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:str1,@"State_Name",str2,@"Name",str3,@"Address",str4,@"Ph", nil];
谁能告诉我这段代码有什么问题吗?我是否以错误的方式使用 nsdictionary?
谢谢
I am having problem initializing nsdictionary and adding it to array. I tried two appoaches but failed in both. My dictionary is always null.
Appoach1:
NSMutableDictionary *Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1",@"State_Name",@"2",@"Name",@"3",@"Address",@"4",@"Ph", nil];// initialized in viewdidload
-(void)find:(NSInteger)Item{
switch (Item) {
case 0:
[Data setValue:string forKey:@"State_Name"];
break;
case 1:
[Data setValue:string forKey:@"Name"];
break;
case 2:
[Data setValue:string forKey:@"TAddress"];
break;
case 3:
[Data setValue:string forKey:@"Ph"];
break;
default:
break;
}
}
Approach2:
NSMutableDictionary *Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:str1,@"State_Name",str2,@"Name",str3,@"Address",str4,@"Ph", nil];
Could any one tell whats wrong with this code. Am I using nsdictionary's in a wrong way?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我执行了你的代码
你需要做的改变是:-
在您的 .h 文件中写入:-
在您的 .m 文件中写入:-
I executed your code
What change you have to do is:-
in your .h file write:-
in your .m file write:-
代码看起来正确。我的猜测是
string
为零。setValue:forKey:
允许 nil(进而删除现有对象)。尝试
setObject:forKey:
,如果 value(string) 为 nil 或检查 string 是否为 nil ,它将引发异常...Code looks correct. My guess is
string
is nil.setValue:forKey:
allows nil (in turn removes existing object).try
setObject:forKey:
, it will raise exception if value(string) is nil or check if string is nil ...对于您的第一种方法:
您的密钥到底是什么以及您在初始化程序中的价值是什么?
在我看来你混淆了顺序。
除此之外:您将字符串放入字典中,但在开关中引用 nsinteger 。您是否在两者之间进行转换?
To your first approach:
What exactly is spposed to be your key and what your value in the initialiser?
It seems to me you mixed up the order.
Besides that : you put strings into the dictionary but refere to a nsinteger in your switch. Are you doing a conversion somewhere in between ?