开发者

Releasing Unused properties in iOS

I have this property synthesized and declared in my class 'ClassA'

@interface ClassA
    @property (no开发者_开发知识库natomic, retain) NameFieldCell* nameCell;
@end

I know that the rule says that the nameCell property should be released in my dealloc method when it is declared with retain|copy|...

However, 'ClassA' gets instantiated lazily and sometimes the nameCell property is not even used, which means that I don't use its setter method nor access it nor retain it explicitly.

Should I still be calling [nameCell release] in my dealloc method? I find it difficult to understand that I should be releasing something that is not even initialized. And since it is not initialized, the reference counter is 0 and makes no sense to release it? Or is nameCell somehow retained automatically when instantiating 'ClassA' even if I am not making use of it?


In Objective-C, the memory allocated by alloc for a class is initialized to all-bits-zero on allocation (and then the isa ivar is set), which results in nameCell's backing ivar being set to nil by default. And since it is not an error to send a message to nil in Objective-C (the message is just ignored), you are free to just call [nameCell release] without worrying about whether nameCell was ever set.


If nameCell is nil, then [nameCell release] has no effect. This makes it easy to cover both cases, so yes, you should release it in your dealloc method.

That or start using ARC, and you won't have to worry about it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜