SomeObject *temp = [[SomeObject alloc] init]
self.theObject = temp;
[temp release];
为什么总是这样?为什么不
self.theObject = [[SomeObject alloc] init];
SomeObject *temp = [[SomeObject alloc] init]
self.theObject = temp;
[temp release];
为什么总是这样?为什么不
self.theObject = [[SomeObject alloc] init];
如果theObject
属性是保留属性,第一种方法是正确的,因为它不会泄漏内存。它也比编写第二个版本的正确方法更有效,即:
self.theObject = [[[SomeObject alloc] init] autorelease];
每当您创建一个对象时,alloc
您都负责以某种方式释放它,无论是 byrelease
还是autorelease
.
第二个版本泄漏了 SomeObject 实例,因为 self.theObject 将调用一个设置器,如果编写得当,它会保留该对象。
你可以做
theObject = [[SomeObject alloc] init];
有些人肯定会这样做。但其他人更喜欢始终使用访问器,无论是为了一致性还是为了避免访问器有副作用时的错误(例如,您将绕过 KVO 通知,如果它不是 init 方法的一部分,这可能是一个问题)。