数组addObject会更改所有数组值,而不仅仅是追加 [英] Array addObject is changing all array values instead of just appending

查看:37
本文介绍了数组addObject会更改所有数组值,而不仅仅是追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我发现了addObject的问题,它不是将值附加到数组的末尾,而是将其放在我要添加的对象的内存位置中(我一遍又一遍地重复使用).最终结果是数组中的所有值最终都完全相同,这与最后一个条目是一样的.显然,我不要这个.

So I have found an issue with addObject where instead of appending a value to the end of an array, its just putting in the memory location of my object that I am adding(which i am re-using over and over). The end result is all the values in the array end up being the exact same, which is whatever the last entry was. Obviously, I don't want this.

如何将唯一的对象添加到数组?这是我添加对象的代码...

How can I add a unique object to the array? This is my code to add the object...

     [listArray addObject:customer];

listArray是一个MSMutable数组.客户是具有4个值的类.

listArray is an MSMutable array. Customer is a class with 4 values.

我在这里发现了同样的问题 addObject在所有数组中创建相同的值

I found this same issue here addObject creates a same value in all array

但是该解决方案给我一个错误,提示:线程1:程序收到信号:"SIGABRT".

but that solution gives me an error of 'Thread 1: Program received signal: "SIGABRT".

我使用代码创建客户对象.

I create the customer object using the code..

      else if ([elementName isEqualToString:@"CustomerListResponse"]) {
         NSLog(@"customer element found – create a new instance of Customer class...");
         customer = [[CustomerListData alloc] init];
      }

谢谢.

推荐答案

您首先应该让客户对象实现NSCopying 协议.然后,您可以执行以下操作:

You first should make your customer object implement the NSCopying protocol. Then, you can do the following:

[listArray addObject:[[customer copy] autorelease]];

这将确保将 new 对象添加到数组中,而不仅仅是指向您不断重复使用的现有对象的指针.

This will ensure that a new object is added to the array instead of just a pointer to the existing object that you are constantly reusing.

请注意,您必须自动释放此副本,因为 copy 方法将返回保留计数为1的新对象.

Note that you have to autorelease this copy as the copy method returns a new object with a retain count of 1.

这篇关于数组addObject会更改所有数组值,而不仅仅是追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆