Trihedron
Trihedron

Reputation: 276

Effective way to modify an NSMutableArray inside a NSMutableDictionary

Just learning and trying new things. I wonder if there is a better way to write this statement, or to modify an array inside of a dictionary. Looking for formatting, memory, and efficiency suggestions:

NSMutableArray *arrayCopy = [self.sortedTimeZonesDictionary objectForKey:currentTimeZone.sectionKey];
[arrayCopy addObject:currentTimeZone];
[self.sortedTimeZonesDictionary setObject:arrayCopy forKey:currentTimeZone.sectionKey];

Where my Dictionary is define as:

@property (strong, nonatomic) NSMutableDictionary *sortedTimeZonesDictionary;

and is alloc'ed and init'ed with an array inside of each key.

Upvotes: 0

Views: 82

Answers (1)

lucaslt89
lucaslt89

Reputation: 2451

you could do only this:

[[self.sortedTimeZonesDictionary objectForKey:currentTimeZone.sectionKey] addObject:currentTimeZone];

Remember that you use pointers, so lets say that your NSMutableDictionary have a pointer to ArrayA, you only need to add an object to ArrayA.

What you are doing in your example is make arrayCopy point to the same memory address than your NSMutableDictionary object, and then add a new object in the array in that memory address. Last instruction won't have any effect since arrayCopy and self.sortedTimeZonesDictionary[currentTimeZone.sectionKey] points to the same address.

Upvotes: 2

Related Questions