Mord Fustang
Mord Fustang

Reputation: 1553

How to add an array to a key in nsdictionary

I want to add an array to a key in nsdictionary. Such as each key is a question and each questions has multiple answers.

Question1 = [Answer1], [Answer2] , [Answer3];

Question2 = [Answer1], [Answer2] , [Answer3];

With below code I get No Visible @interface for NSDictionary declares the selector '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"];

What is correct way to add an array to a key in NSDictionary?

Upvotes: 1

Views: 3910

Answers (2)

Adam Levy
Adam Levy

Reputation: 97

Although you are instantiating _surveyAnswers1 as an NSMutableDictionary, it's declared as an NSDictionary type so either change _surveyAnswers1 to be NSMutableDictionary type or cast _surveyAnswers1 to NSMutableDictionary when you call setObject:forKey:

[((NSMutableDictionary *)_surveyAnswers1) setObject:myArrayAnswers1 forKey:@"FirstKey"];
[((NSMutableDictionary *)_surveyAnswers1) setObject:myArrayAnswers2 forKey:@"SecondKey"];

Upvotes: 2

jscs
jscs

Reputation: 64002

_surveyAnswers1 seems to be declared as an NSDictionary:

NSDictionary * _surveyAnswers1;

You need to declare it as NSMutableDictionary:

NSMutableDictionary * _surveyAnswers1;

The compiler checks what methods are available on the object based on its declared type; NSDictionary does not have the method setObject:forKey:, so the compiler warns you (under ARC, this is an error) about that. It would work at runtime, because the object actually is an NSMutableDictionary, but you should still fix the declaration.

Upvotes: 4

Related Questions