如果我多次调用nsobject init会发生什么?它增加保留人数吗? [英] What happens if i call nsobject init more than once? Does it increase retain count?
问题描述
我对Objective-C还是很陌生,我在内存管理方面遇到很多麻烦,但我还是有些了解.如果我有一个对象,例如NSArray * myArray,我就这样做
I'm pretty new to Objective-C and i have lots of troubles with memory management and still i understand a little. If i have an object, NSArray * myArray for example, and i do this
myArray = [[NSArray alloc] initWithObjects:obj1,obj2,obj3,nil];
然后我正在做某事,我希望myArray包含新对象,然后再次将其初始化
then i'm doing something and i want myArray to contain new objects and then i init it again
[myArray initWithObjects:obj4,obj5,obj6, nil];
似乎可以满足我的需要,但是从内存管理的角度来看这是否正确?它会增加保留计数吗?那我应该释放两次吗?
seems like it does what i need but is it correct grom the point of view of memory management?does it increase retain count? should i release it twice then?
推荐答案
不要那样做!
通常,如果要重置对象或已存在的Objective C对象中的事物,请创建并使用某种Setter方法.
In general, if you want to reset the objects or things inside an already existing Objective C object, create and use some kind of Setter method.
对于您的阵列,再次不要这样做!您引用的"initWithObjects"方法可以方便地初始化一个不可变(不可更改)数组,其中包含将在整个生命周期内填充数组的项目.
For your array, again do not do this! The "initWithObjects" method you cite is a convenience to initialize a immutable (non-changeable) array with the items an array will be populated with over it's entire lifetime.
对于您要尝试执行的操作,只需使用NSMutableArray.下面列出了它的文档:
For what you are trying to do, just use NSMutableArray. The documentation for it is listed below:
这篇关于如果我多次调用nsobject init会发生什么?它增加保留人数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!