局部变量赋值与直接赋值;属性和记忆 [英] Local variable assign versus direct assign; properties and memory

查看:117
本文介绍了局部变量赋值与直接赋值;属性和记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我看到很多示例代码,其中作者分配了一个局部变量,将其分配给一个属性,然后释放了该局部变量.有实际的理由吗?在大多数情况下,我一直只是直接分配给该属性.会以任何方式引起内存泄漏吗?我想我想知道两者之间是否有任何区别:

In objective-c I see a lot of sample code where the author assigns a local variable, assigns it to a property, then releases the local variable. Is there a practical reason for doing this? I've been just assigning directly to the property for the most part. Would that cause a memory leak in any way? I guess I'd like to know if there's any difference between this:

HomeScreenBtns *localHomeScreenBtns = [[HomeScreenBtns alloc] init];
self.homeScreenBtns = localHomeScreenBtns;
[localHomeScreenBtns release];

和这个:

self.homeScreenBtns = [[HomeScreenBtns alloc] init];

假设homeScreenBtns是这样的属性:

Assuming that homeScreenBtns is a property like so:

@property (nonatomic, retain) HomeScreenBtns *homeScreenBtns;

我准备将应用程序提交到应用商店,因此处于完全优化/质量检查模式.

I'm getting ready to submit my application to the app store so I'm in full optimize/QA mode.

推荐答案

您不能这样做:

self.homeScreenBtns = [[HomeScreenBtns alloc] init];

因为[[HomeScreenBtns alloc] init]时创建了一个带有alloc的对象,所以该对象的保留计数为1.然后,将该对象设置为homeScreenBtns时,其保留计数为2,因为homeScreenBtns也保留了该对象. .因此,对象的保留计数永远无法恢复为0,因为唯一的释放语句在homeScreenBtns的setter方法中.因此,您会泄漏内存.如果您想在一个语句中而不是您列出的第一种方法中进行操作,则可以使用:

because when you [[HomeScreenBtns alloc] init] you create an object with alloc so that object has a retain count of 1. Then when you set that object to homeScreenBtns it has a retain count of 2 because homeScreenBtns also retains that object. Thus the retain count of the object can never get back to 0 because the only release statement is in the setter method of homeScreenBtns. Thus you leak memory. If you want to do it in one statement instead of the first way you listed you could use:

self.homeScreenBtns = [[[HomeScreenBtns alloc] init] autorelease];

这篇关于局部变量赋值与直接赋值;属性和记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆