使用@property和@synthesize时防止泄漏 [英] Preventing leaks when using @property and @synthesize

查看:63
本文介绍了使用@property和@synthesize时防止泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用@property@synthesize时,我们应该采取什么步骤-最佳做法是什么?以防止泄漏?

What steps should we take -- what are the best practices -- to prevent leaks when using @property and @synthesize?

推荐答案

请注意一些标准的东西,这些东西会带给您保留的对象,带有alloc,copy或new的方法.当您将这些连同属性一起调用时,可能会无意间造成泄漏.

Be aware of your standard things that give you back retained objects, methods with alloc, copy or new. When you invoke these along with your property you can inadvertently create a leak.

在您的界面中,您有

@property (nonatomic, retain) NSArray *someArray;

在您的实现中,您已经拥有

And in your implementation you have

@synthesize someArray;

然后稍后使用该属性

self.someArray = [[NSArray alloc] init];

您的对象现在的保留计数为2.一个使用self.someArray =,另一个来自alloc. self.someArray =调用与-(void)setSomeArray:(NSArray)someArray;相同的setter;通过合成为您创建的.由于您在@property声明中使用了keep关键字,因此将包含一个keep.

your object now has a retain count of 2. one from using self.someArray = and one from the alloc. self.someArray = invokes your setter which is the same as - (void)setSomeArray:(NSArray)someArray; which is created for you with the synthesize. This is going to contain a retain because of the retain keyword you used in the @property declaration.

我倾向于避免以下两种方法之一.

I tend to avoid this one of two ways.

使用自动释放的初始化器

either with using the autoreleased intializer

self.someArray = [NSArray array];

self.someArray = [[[NSArray alloc] init] autorelease];

或使用临时变量

NSArray tempArray = [[NSArray alloc] init];
self.someArray = tempArray;
[tempArray release];

所有这些方法都将使您留下一个self.someArray对象,该对象的保留计数为1,您可以在dealloc中进行处理.

all of these methods will leave you with your self.someArray object having a retain count of one which you can take care of in the dealloc.

- (void)dealloc {
[someArray release];
[super dealloc];
}

这篇关于使用@property和@synthesize时防止泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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