Does “self.propery = [[SomeClass alloc] init];” leak memory?

大城市里の小女人 提交于 2019-12-31 06:40:21

问题


Is it safe in Objective-C to write

self.propery = [[SomeClass alloc] init];

instead of

SomeClass *tmp = [[SomeClass alloc] init];
self.property = tmp;
[tmp release];

or will the first form leak memory?


回答1:


The first example leaks unless you provide a custom property setter. You can use:

self.propery = [[[SomeClass alloc] init] autorelease];

Instead.




回答2:


It depends on how the property is defined. If it's defined with retain or copy then, yes, your first example will leak.




回答3:


The first one will leak.

You must release or autorelease anything you [[ alloc] init] when you don't need it anymore.

Refer to this guide.




回答4:


It doesn't make a bit of difference whether or not your property is defined as retain, copy, or assign. When you create a local instance of a class with [[SomeClass alloc] init], you are responsible for releasing it within the scope it was created.

Kevin's response is correct. If you do not feel like creating, setting, releasing - you can use autorelease. The main autorelease pool is drained from time to time, you will not be using that memory for the lifetime of the application.

It is worth noting that the unpredictable nature of autorelease pools means that you can not be sure when that memory will be released. If working in a memory constrained platform like the iPhone, you should avoid using autorelease except in places where necessary.



来源:https://stackoverflow.com/questions/3549649/does-self-propery-someclass-alloc-init-leak-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!