我想在nsdictionary中为一个键添加一个数组。比如每个关键字都是一个问题,每个问题都有多个答案。
问题1 = [答案1],[答案2],[答案3];
问题2 = [答案1],[答案2],[答案3];
使用下面的代码我得到没有Visible @interface for NSDictionary声明选择器'setObject:forKey:'
//answers
_surveyAnswers1 = [[NSMutableDictionary alloc] init];
NSArray *myArrayAnswers1 = [NSArray arrayWithObjects:@"One",@"Two", nil];
NSArray *myArrayAnswers2 = [NSArray arrayWithObjects:@"Three",@"Four", nil];
[_surveyAnswers1 setObject:myArrayAnswers1 forKey:@"FirstKey"];
[_surveyAnswers1 setObject:myArrayAnswers2 forKey:@"SecondKey"];
在NSDictionary中为数组添加数组的正确方法是什么?
答案 0 :(得分:4)
_surveyAnswers1
似乎被声明为NSDictionary
:
NSDictionary * _surveyAnswers1;
您需要将其声明为NSMutableDictionary
:
NSMutableDictionary * _surveyAnswers1;
编译器根据声明的类型检查对象上可用的方法; NSDictionary
没有方法setObject:forKey:
,因此编译器会警告您(在ARC下,这是一个错误)。它可以在运行时工作,因为对象实际上是 NSMutableDictionary
,但你仍然应该修复声明。
答案 1 :(得分:2)
虽然您将_surveyAnswers1实例化为NSMutableDictionary,但它被声明为NSDictionary类型,因此当您调用setObject:forKey时,将_surveyAnswers1更改为NSMutableDictionary类型或将_surveyAnswers1强制转换为NSMutableDictionary:
[((NSMutableDictionary *)_surveyAnswers1) setObject:myArrayAnswers1 forKey:@"FirstKey"];
[((NSMutableDictionary *)_surveyAnswers1) setObject:myArrayAnswers2 forKey:@"SecondKey"];