简体   繁体   English

“ self.propery = [[SomeClass alloc] init];”是否泄漏内存?

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

Is it safe in Objective-C to write 在Objective-C中编写安全吗

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

instead of 代替

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

or will the first form leak memory? 还是第一种形式会泄漏内存?

The first example leaks unless you provide a custom property setter. 第一个示例泄漏,除非您提供自定义属性设置器。 You can use: 您可以使用:

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

Instead. 代替。

It depends on how the property is defined. 这取决于属性的定义方式。 If it's defined with retain or copy then, yes, your first example will leak. 如果是使用“保留”或“复制”定义的,那么是的,您的第一个示例将泄漏。

The first one will leak. 第一个将泄漏。

You must release or autorelease anything you [[ alloc] init] when you don't need it anymore. 如果不再需要[[ alloc] init] ,则必须释放或自动释放它们。

Refer to this guide . 请参阅本指南

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. 使用[[SomeClass alloc] init]创建类的本地实例时,您有责任在创建它的范围内释放它。

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. 如果在内存受限的平台(例如iPhone)上工作,则除非必要,否则应避免使用自动释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM