自动释放与释放
当我需要一个临时使用的数组时,这些之间有什么区别:
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
我更喜欢数字 2,因为它更短。使用数字 1 或 3 有什么充分的理由吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在大多数情况下,2 号可能是最佳选择。
无论出于何种原因,Number 1 有可能在某个时刻丢失释放,但它确实会立即释放数组,这在内存匮乏的环境中可能很有用。
数字 3 基本上是数字 2 的详细等效项,但如果您想使用没有相应 arrayWith* 的 initWith* ,它确实会派上用场。
注意:如果您内存不足,例如在一个昂贵的循环中,每次迭代都需要一个新的数组; 不要释放和分配新数组;只需使用 -removeAllObjects 并回收数组即可。
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.