Reputation: 7588
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?
Upvotes: 1
Views: 47
Reputation: 11928
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];
EDIT:
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];
Upvotes: 3
Reputation: 8322
you need to copy that object as below :
_myArray =[[NSMutableArray arrayWithArray:[[[DataCenter singleton] myDict] allValues]]mutableCopy];
Upvotes: 0