开发者

Creating an Array of Arrays in XCode

开发者 https://www.devze.com 2022-12-12 03:50 出处:网络
I am trying to build an array that contains arrays of dictionary objects in Xcode.I can create a working array that has one or more dictionaries in it and then use the addObject: method to add this ar

I am trying to build an array that contains arrays of dictionary objects in Xcode. I can create a working array that has one or more dictionaries in it and then use the addObject: method to add this array as an object in my main array. I cycle around this several times, rebuilding the working array and adding objects to the main array. All good so far, except that on inspecting my main array it contains duplicates of the last dictionaries 开发者_StackOverflowthat the working array was built with. I am assuming this is because when I use the addObject it simply assigns a pointer to the array but does not increase the retain count or create a copy of the working array, hence every time it is rebuilt the main array simply points to the this array.

I guess my question is how do I create a copy of the working array add it to the main array and then rebuild it and add it again? Hope that makes sense and sorry if this appears to be a basic question - it is (I'm new to Xcode) - and any help would be really appreciated.


        [sectionArray release];
        sectionArray  = [[NSMutableArray alloc] init];
        [sectionArray addObject:dict];

This all works, which is great. One thing I don't have my head around yet is, is there a danger that when I am done with the main array and I do a [mainArray release] too that these child arrays will be left behind in memory or will the release destroy them as well?


I have solved it by re-initialising the inner working array instead of just removing all objects, i.e.,

I did have:

        [sectionArray removeAllObjects];
        [sectionArray addObject:dict];

And changed it to:

        sectionArray  = [[NSMutableArray alloc] init];
        [sectionArray addObject:dict];

I have a feeling though that this is not a good thing to do and I will start to leak memory all over the place.


If all you do with sectionArray is to put it in another array you need to release it after you put it in your mainArray so that only mainArray holds a reference to it:

sectionArray = [[NSMutableArray alloc] init];
[sectionArray addObject:dict];
[mainArray addObject:sectionArray];
[sectionArray release];

When you later release your mainArray reference it will take care of releasing all it's children and your sectionArray's will be freed. (The same goes for the dicts put in sectionArray).

Hope this helped.

0

精彩评论

暂无评论...
验证码 换一张
取 消