填充 NSMutableArray 时重复
我试图将两个对象添加到我的数组中,但是当我检查数组时,第二个对象在列表中出现两次。有谁知道为什么?
list = [[NSMutableArray alloc] init];
Person *person = [[Person alloc] init];
// Create person 1
person.name = @"Fred";
person.gender = @"unknown";
// Append to array
[list addObject:person];
[person release];
// Create person 2
person.name = @"Bob";
person.gender = @"male";
// Append to array again
[list addObject:person];
[person release];
I am trying to add two objects to my array but when i inspect the array, the second object appears in the list twice. Does anyone know why?
list = [[NSMutableArray alloc] init];
Person *person = [[Person alloc] init];
// Create person 1
person.name = @"Fred";
person.gender = @"unknown";
// Append to array
[list addObject:person];
[person release];
// Create person 2
person.name = @"Bob";
person.gender = @"male";
// Append to array again
[list addObject:person];
[person release];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您创建的不是两个人的实例,而是一个人的实例。
要么这样做:
要么将第二个人分配给第二个变量。
person
变量仍然指向第一个人实例。您需要将变量更改为新实例,否则您只需将人员插入两次并覆盖其属性。You're not creating two person instances, but just one.
Either do this:
or assign a second person to a second variable.
The
person
variable still points to the first person instance. You need to change the variable to a new instance, otherwise you're simply inserting the person twice and also overwriting its properties.问题在于该数组不会复制您传递给它以添加的对象,而是仅保存对该对象的引用。因此,您要做的就是创建一个对象,分配给它的属性,提供对数组的引用,改变同一个对象,然后再次将相同(但改变了)的对象添加到数组中。
您每次都需要创建一个新的 Person 对象,而不是改变同一个对象。
The problem is that the array does not make a copy of the object you passed to it to add, instead it only holds a reference to the object. So what you're doing is creating an object, assigning to its properties, giving a reference to the array, mutating the same object, and then adding the same (but mutated) object to the array again.
You need to make a new Person object each time instead of mutating the same object.
你只创造了一个人。试试这个:
这里的问题是,当你将第一个人添加到数组中,然后修改原始对象时,数组中的对象也被修改了——你需要实例化一个新版本的“人”对象并修改它。
如果你想创建很多很多人,我建议使用
for
循环:You've only created one person. Try this:
The issue here is that when you added the first person to the array, and then modified the original object, the object is also modified in the array --- you need to instantiate a new version of the "person" object and modify it.
If you want to create many, many people, I suggest using a
for
loop: