-1

The question is as simple as the title:

Is a NSMutableDictionary in a NSDictionary still mutable? Is the mdict mutable below?

NSMutableDictionary *mdict = [[NSMutableDictionary alloc] init];
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:mdict, @"key", nil];

And, is a NSDictionary in a NSMutableDictionary still immutable?

Further, what if it's array/set instead of dictionary?

Stephenye
  • 806
  • 6
  • 12

3 Answers3

1

Absolutely! Mutability of an object does not change when you place it into a container.

When you place a mutable dictionary into another collection, mutable or immutable, that collection adds a reference to the mutable dictionary object, but it does not change it in any other way. Same goes for placing immutable objects into collections: collections reference these objects without changing their nature.

This remains true while your object is in memory. If you serialize it and then deserialize it back, the process of deserialization may remove mutability. For example, if you save NSMutableDictionary into NSUserDefaults and then read it back, you would get back an immutable dictionary.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Yes. Objects generally don't know when they're placed into a collection, so they can't change their behavior based on that. NSDictionary does copy its keys (precisely so you can change the original object without affecting the dictionary), but it just stores a normal reference to the value.

Chuck
  • 234,037
  • 30
  • 302
  • 389
0

As long as you access your variables like so

 NSMutableDictionary * tempDict = [mdict objectForKey: @"Key"];
 NSMutableDictionary * tempDict2 = [arrayVar objectAtIndex: index];

The temp variables retain all the functionality as before

V-FEXrt
  • 11
  • 3