使用@property和@synthesize时防止泄漏
在使用 @property
和 @synthesize
时,我们应该采取哪些步骤(最佳实践是什么)来防止泄漏?
What steps should we take -- what are the best practices -- to prevent leaks when using @property
and @synthesize
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意您的标准事物,这些事物会返回保留的对象、带有 alloc、copy 或 new 的方法。当您将这些与您的属性一起调用时,您可能会无意中造成泄漏。
在你的接口中你有
,在你的实现中你有
然后你使用
你的对象现在的保留计数为2的属性。一个来自使用self.someArray =,一个来自alloc。 self.someArray = 调用与 - (void)setSomeArray:(NSArray)someArray 相同的 setter;这是通过合成为您创建的。由于@property 声明中使用了retain 关键字,因此它将包含retain。
我倾向于通过以下两种方式之一来避免这种情况。
无论是使用自动释放的初始化程序
还是
使用临时变量,
所有这些方法都会让您的 self.someArray 对象的保留计数为 1,您可以在 dealloc 中处理该对象。
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.
In your interface you have
And in your implementation you have
Then later on you use the the property
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
or
or use a temp variable
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.
对我帮助很大的一件事是检查头文件中是否有保留类型的属性定义,然后确保 -dealloc 方法中每个属性都有一个版本。
对于对象生命周期内对属性的各种分配,自动合成的设置器应该处理它。
One thing that has helped me a lot is to check your header file for property definitions with a retain type, and then make sure that there is a release for each of them in the -dealloc method.
For the various assignments to the properties during the lifetime of the object, the automatic synthesized setters should take care of it.