Dan Morgan
Dan Morgan

Reputation: 2500

Mutable Object within an Immutable object

Is it acceptable to have a NSMutableArray within an NSDictionary? Or does the NSDictionary also have to be mutable?

The NSMutableArray will have values added to it at runtime, the NSDictionary will always have the same 2 NSMutableArrays.

Thanks,

Dan

Upvotes: 2

Views: 261

Answers (2)

Mike Abdullah
Mike Abdullah

Reputation: 15003

It's quite acceptable. But, it's precisely the sort of setup that suggests you should seriously consider replacing the dictionary with an NSObject subclass that sports two properties for accessing the arrays.

Upvotes: 0

drewh
drewh

Reputation: 10167

Yes, it's perfectly acceptable. Keep in mind, the contents of the array are the pointers to your NSMutableArrays--those are what can't change in the immutable dictionary structure. What the pointers point to can change all you want. To wit:

NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary *dict = [NSDictionary dictionaryWithObject:arr forKey:@"test"];

[arr addObject:@"Hello"];
NSString *str = [[dict objectForKey:@"test"] objectAtIndex:0];
NSLog("%@", str);

Upvotes: 3

Related Questions