Autorelease vs. release

不羁的心 提交于 2019-12-18 13:37:11

问题


When I need an array for temporary use, what's the difference between these:

1:

NSMutableArray *stuff = [[NSMutableArray alloc] init];
// use the array
[stuff release];

2:

NSMutableArray *stuff = [NSMutableArray array];
// use the array

3:

NSMutableArray *stuff = [[[NSMutableArray alloc] init] autorelease];
// use the array

I prefer number 2, since it's shorter. Are there any good reasons to use number 1 or 3?


回答1:


Number 2 is likely the best choice in most cases.

Number 1 has the chance of losing the release at some point down the line, for whatever reason, but it does release the array immediately, which in memory-starved environments can be useful.

Number 3 is basically a verbose equivalent of number 2, but it does come in handy if you want to use an initWith* that doesn't have a corresponding arrayWith*.

Note: If you are memory-starved, such as in an expensive loop where you need a fresh array for each iteration; don't release and allocate new arrays; just use -removeAllObjects and recycle the array.



来源:https://stackoverflow.com/questions/4077159/autorelease-vs-release

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