Rocotilos Rocotilos - 9 months ago 47
iOS Question

NSMutableArray auto updates with Dictionary in singleton

I have a weird problem. I have a singleton with dictionary in it. This dictionary is updated regularly in runtime. In a viewcontroller I access this singleton dictionary and create a new NSMutableArray.

@property (nonatomic, retain) NSMutableArray *myArray;

Initialized it in viewDidload:

_myArray = [[NSMutableArray alloc] init];

Then in viewDidAppear, I assign the array to the singleton NSMutableDictionary *myDict values:

_myArray = [NSMutableArray arrayWithArray:[[[DataCenter singleton] myDict] allValues]];

Before doing anything to _myArray, I monitor _myArray values in a timer and it seems that it always keep on changing following the singleton dictionary values.

Why and how to create an independent NSMutableArray that isn't somehow tied to this dictionary singleton?

Answer Source

It's not a weird problem, it's how Objective-C works. Your singleton array is just a collection of object references. You've filled _myArray with those exact same references. All modifications in one will be reflected by the other because, well, they're the same objects.

In order to actually make new objects, you need to make a copy. Something like this:

_myArray = [[NSMutableArray alloc] initWithArray:[[[DataCenter singleton] myDict] allValues] copyItems:YES];


I can't test with [[[DataCenter singleton] myDict] allValues] in my compiler, but a contrived example incase you want to experiment with deepCopy and array.

NSArray *array = [NSArray arrayWithObject:@"foo"];
NSMutableArray* _myArray = [[NSMutableArray alloc] initWithArray:array copyItems:YES];