0

I have a dictionary and want to add a new object to it but compiler give error that it not mutable.

like code below:

dict[@"key"] = @"something new";
John
  • 3
  • 1
  • Already asked and answered: https://stackoverflow.com/questions/6519957/add-values-in-nsmutabledictionary-in-ios-with-objective-c – fisehara Sep 27 '17 at 15:05
  • Show us the exact error message. If the dictionary is defined and init as a `NSDictionary`, why not using `NSMutableDictionary` instead? – Larme Sep 27 '17 at 15:09
  • Possible duplicate of [Add values in NSMutableDictionary in iOS with Objective-C](https://stackoverflow.com/questions/6519957/add-values-in-nsmutabledictionary-in-ios-with-objective-c) – Andrey Belykh Sep 27 '17 at 15:34

2 Answers2

0

You are trying to mutate an immutable object. You need to create a mutable copy and the add the new key-value

NSMutableDictionary *mut = [dict mutableCopy];
mut[@"new key"] = @"new value";
Avba
  • 14,822
  • 20
  • 92
  • 192
0

If you want to keep the dictionary immutable, you can do:

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:@"something new", @"key", nil];