简体   繁体   English

Objective-C:在构造函数中,自动释放的初始化后跟一个保持错误吗?

[英]Objective-C: Is an autoreleased initialisation followed by a retain wrong in a constructor?

In my @interface theres a NSArray *Monate followed by: 在我的@interface有一个NSArray *Monate其后是:

@property (nonatomic, retain) NSArray* Monate;

If i do: 如果我做:

filePath = [[NSBundle mainBundle] pathForResource:@"SomeFile" ofType:@"plist"];
self.Monate = [NSArray  arrayWithContentsOfFile:filePath];

in the constructor, it gets set to an autoreleased object (is that correct?). 在构造函数中,将其设置为自动释放的对象(对吗?)。 So should I do a [Monate retain] afterwards? 那之后我应该做[Monate retain]吗?

This code is correct; 该代码是正确的; you should not add a retain call. 您不应该添加保留呼叫。

+[NSArray arrayWithContentsOfFile:] will return an autoreleased NSArray . +[NSArray arrayWithContentsOfFile:]将返回自动释放的NSArray Passing that to -[YourClass setMonate:] will retain the object and assign to the backing ivar. 将其传递给-[YourClass setMonate:]将保留该对象并分配给后备ivar。 After the constructor returns, the new NSArray will have a retain count of 2 and be added once to the current autorelease pool (resulting in a net retain count of 1) 构造函数返回后,新的NSArray的保留计数为2,并一次添加到当前自动释放池中(净保留计数为1)

As long as you release the array in your dealloc, this code is correct. 只要您在dealloc中释放该数组,此代码就是正确的。

You should NOT do a retain after. 之后您不应该保留。 By setting a @property of retain, some special things happen when you use the self.Monate setter 通过设置保留的@property,当您使用self.Monate setter时会发生一些特殊的事情

1) Anything in the Monate instance variable, if any, will get a release. 1)Monate实例变量中的任何内容(如果有)将得到释放。
2) the new assignment will get a retain. 2)新的任务将被保留。

if you were to use @property of assign, then you would have to retain, but you are fine the way you are. 如果您要使用@property的assign,那么您将必须保留,但您的状况会很好。

As a side note, in objective-c, Capitalized words are usually reserved for Class names. 附带说明,在目标c中,大写单词通常保留用于类名称。 I sugges changin it to "monate" instead of "Monate" as this could lead to confusion down the road 我建议将其更改为“ monate”而不是“ Monate”,因为这可能会导致混乱

[NSArray arrayWithContentsOfFile:]; [NSArray arrayWithContentsOfFile:]; returns an autoreleased array which will require retaining if you want it to hang around longer than the end of the method. 返回一个自动释放的数组,如果您希望它比方法结尾更长的时间,则需要保留该数组。

Notice how your property declaration specifies 'retain'. 注意您的属性声明如何指定“保留”。 This means that any self.property = x; 这意味着任何self.property = x; calls you do will retain the object you pass in. 您执行的呼叫将保留您传递的对象。

So what you are doing there is correct. 因此,您在那做的是正确的。 Just remember to do self.property = nil; 只记得做self.property = nil; in your dealloc method. 在您的dealloc方法中。

Setting a property to nil will release the old object and set the pointer to nil, which is the correct way to do it. 将属性设置为nil将释放旧对象,并将指针设置为nil,这是正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM