使用点语法设置保留属性时使用autorelease?

我看到在一些示例代码中使用autorelease 。 我不熟悉需要的情况。 例如,如果我创build一个注释对象

头文件

 @interface someViewController: UIViewController { Annotation *annotation; } @property (nonatomic, retain) Annotation *annotation; @end 

实施文件

 @implementation someViewController @synthesize annotation @end 

问题:如果我像这样初始化实现文件中的注释对象,是否是正确的方法?

 self.annotation = [[Annotation alloc] initWithCoordinate:location]; 

我需要为此设置autorelease吗? 或者我可以按照正常的方式做,并在dealloc方法中添加发行版?

这是对的:

self.annotation = [[[Annotation alloc] initWithCoordinate:location] autorelease];

因为注解属性被声明为一个保留属性,所以分配给它会增加其保留计数。

你也需要,在-dealloc释放-dealloc

简而言之:

  1. init将保留计数设置为1;

  2. 分配给self.annotation,将它设置为2;

  3. 当主循环再次执行时,autorelease会将其设置回1;

  4. 释放dealloc将设置保留计数为0,以便该对象将被释放);

在我看来, autorelease最好的方法是:在我看来, autorelease会在将来的某个点(接近)为你的对象“计划”一个“自动” release (通常当控制stream返回到主循环时,细节隐藏在苹果手中)。

autorelease主要与init结合使用,特别是在以下情况下:

  1. 当你init一个局部variables的时候,你不需要在它超出范围之前明确地release它(主循环会为你做)。

  2. 当你返回一个指向刚刚创build的对象的指针而不保留它的所有权时( create/make*types的select器的典型例子,接收者需要retain它以获得所有权)。

  3. 当属性retain ,当你分配给他们一个对象,他们应该拥有唯一的;

  4. 与增加保留计数( NSMutableArrayNSMutableDictionary等)的数据结构:你应该通常autorelease一个新的init对象,当你将它添加到这样的数据结构。

除了情况2以外,显然使用autorelease是为了提高代码的可读性并减less错误的可能性(意味着在所有其他情况下,您可以简单地在分配之后或在范围的末尾)。

当使用属性时,你总是要检查它们是否属于retainassign / copy情况; 在第一种情况下,将新创build的对象分配给属性通常需要autorelease

无论如何,我会build议至less略过iOS的内存pipe理的教程之一。

Autorelease正在告诉对象在离开示波器之前自行释放。

有时当你编码时,你会遇到这样的事情

 - (void)doSomething { if(true) { NSString *foo = [[NSString alloc] initWithString:@"foo"]; //Some execution here [foo release]; } } - (void)doSomething { if(true) { //By doing this is telling to to release foo object before getting out of the scope //which is similar with above practice NSString *foo = [[[NSString alloc] initWithString:@"foo"] autorelease]; //Or you can do it this way NSString *foo = [[NSString alloc] initWithString:@"foo"]; [foo autorelease]; //Some execution carry on, it'll release foo before entering next scope } 

//这是超出范围}

当然,释放对象并不意味着释放对象。 有时你保留这个对象,所以你仍然可以在它的范围之外使用它。

从你的问题来看,如果你的对象位于你的头文件/接口。 你应该释放它在dealloc方法。 CMIIW。