开发者

dealloc and release issue

i know this issue was discussed many times before , but i have a simple question. after reading all the apple's rules to manage the memory, i know this :

if i allocate an object , i own it and have to release it . so i have to do :

ran *me = [[ran alloc] init];
//do somthing
[me release];

so now , the retain count is 0, after i release ran object.

BUT i was also read that when retain count of an object is 0, the dealloc method is being invoked .

so my question is, after i took down the retain count to 0, DO i have to release again the object at the dealloc?

-(void)dealloc
[me release];

or that the first release did the job ? otherwise, why dealloc 开发者_StackOverflow中文版is being called anyway ? if the retain count=0 we are ok no ??

thanks a lot .


No, you do not need to release again in there - in fact, don't do it!

The reason dealloc is being called is so that clean-up may occur. For example, if you allocated memory in your class, you can free it up there. And remember that the retain count could reach 2, 3, 4, 5.... so just because a release is done, you don't (as an outside user of the class) know that the dealloc should be called. That's how it is different than a release.

One thing to note is that the dealloc method may not be immediately run when the count hits 0. It could be done much later.


Depends if the variable "me" is an instance variable, or "ivar" as it's called.

For ivars, you put the release in the dealloc. For everything else, you must release it in the same method you create it.

Unless of course it's an autoreleased object, but that's a different story...


First i think you mean [me release];

Second you only must release it in dealloc if you retained it in the .h file like @property (nonatomic, retain) ran *me;

With this you set the retaincout of *me to 1 then alloc init it to 2 in .m file, then you have to release *me two times. First time for the alloc init, second time in dealloc for the retain in .h

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜