addObject在所有数组中创建相同的值 [英] addObject creates a same value in all array

查看:48
本文介绍了addObject在所有数组中创建相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数组中动态添加元素.为此,我正在使用

I want to add element in the array dynamically. For this I am using

[myArray addObject:myword];

myword is a NSMutableString type object.

在每个按钮上单击myword以获取更改.但是数组的所有元素都存储最后一个值.假设第一次数组具有1个元素="me"第二时间数组应具有2个元素="me","you".但是它显示我",我".可能是什么问题?

on each button click myword get changes. But all the element of array store the last value. Suppose first time the array has 1 element = "me" Second time array should have 2 element = "me", "you". But it shows "me", "me". what may be the problem?

推荐答案

由于您可能会一遍又一遍地存储相同的NSMutableString实例,因此更改它自然会更改所有"元素.毕竟,它们都指向同一个对象.

Since you're probably storing the same instance of NSMutableString over and over again, it's natural that changing it changes "all" elements. After all, they all point to the same object.

尝试:

[myArray addObject:[[myword copy] autorelease]];

或者如果您需要NSMutableStrings:

Or if you need to have NSMutableStrings:

[myArray addObject:[[myword mutableCopy] autorelease]];

此处需要 autorelease ,否则会发生内存泄漏.

You need the autorelease here, otherwise you'd have a memory leak.

这篇关于addObject在所有数组中创建相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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