Supposedly separate NSArray being contaminated by editing a copy

爱⌒轻易说出口 提交于 2019-12-12 04:49:37

问题


I have a TableView with some TextFields in. The values of said TextFields are linked to certain positions in a 2D Array (NSArray of NSMutableArrays).

An initial clean array is defined as so:

self.cleanEditContents = @[
                      [@[@-1,@-1] mutableCopy],
                      [@[@0,@80] mutableCopy],
                      [@[@0,@500] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy],
                      [@[@-1,@-1] mutableCopy]
                      ];

This array is supposed to be kept separate from the 'active' array, so that the active array can be reset on a button press.

I use self.editContents = [self.cleanEditContents copy]; to set the active array both directly after the clean array is populated and on a button press.

There is a problem where even though I reset the array and call reloadData and setNeedsLayout (overkill? probably), the numbers don't reset. I tried outputting the values of the same position in both arrays and it turns out that any changes made to the active array contaminate the clean array.


回答1:


copy does a shallow copy. In other words, self.editContents and self.cleanEditContents both reference the same set of mutable arrays. So if you update a mutable array in one, the change is seen in the other.

To create self.editContents, create a new array with mutable copies of the inner arrays.

NSMutableArray *tmp = [NSMutableArray array];
for (NSArray *array in self.cleanEditContents) {
    [tmp addObject:[array mutableCopy]];
}
self.editContents = tmp;



回答2:


It sounds like you expected a deep copy.

The copy method does a shallow copy, that is it just makes a copy of the array and not of the items in the array.

So when you do [self.cleanEditContents copy] the new array shares exactly the same items as the original.

If you need a deep copy (or maybe just a 2-level copy) you need to code it yourself.



来源:https://stackoverflow.com/questions/27785572/supposedly-separate-nsarray-being-contaminated-by-editing-a-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!