I believe my problem involves pointers, a concept I often struggle with, but here’s what I’m trying to do.
I have six NSArrays. I want an additional NSArray comprised of these six arrays, so:
self.arr1 = [NSArray array];
self.arr2 = [NSArray array];
self.arr3 = [NSArray array];
self.arr4 = [NSArray array];
self.arr5 = [NSArray array];
self.arr6 = [NSArray array];
NSArray *containerArray = [[NSArray alloc] initWithObjects:self.arr1, ... etc, nil];
Whenever I update one of the first 6 NSArrays, I want the object updated in containerArray. (I know I’m using an NSArray and not an NSMutableArray, when I update the arrays I create a new one and assign it to the instance variable).
Currently, any manipulation of arr1 is not reflected in [containerArray objectAtIndex:0].
Because your instance variables
self.arr1,self.arr2are placeholders for a variable of typeNSArray, but when you update them you just lose the old reference that still remains in thecontainerArray.To explain better:
then you build up the
contentArrayand you have:after you create your
contentArrayand you assign the arrays to it you have duplicated references.self.arr1will point to the same array pointed by first element ofcontentArrayand so on for others.Then you update
self.arr1 = [NSArray array]with a new array so what you obtain isSo what’s happened?
You created a new array and assigned it to
self.arr1. Soself.arr1will point to the new item while[contentArray objectAtIndex:0]will still reference to the old one. Every modification toself.arr1will be not reflected on the other one because they are NOT the same object.This because you are using references to objects and not plain objects. When you assign a new array to
self.arr1you are not modifying the old one but discarding the reference to it for a new one that replaces the old one.That’s why you should use a
NSMutableArray: because in that case you would remove/add elements to the same array, without creating a new one.