开发者

Why should I do [object release]; object=nil; when deallocating an object?

I would like to understand why it could 开发者_Go百科be useful to do this (assuming "object" was previously allocated):

[object release]; 
object=nil;

Thx for helping,

Stephane


Even though you release an object, your variable will still point to something. What it points to is undefined. It could still point to the old object, or to some point in memory. Setting it to nil avoids sending messages to whatever it points to, and prevents errors (messaging nil does nothing).

Here's an answer that states it better: Setting pointers to nil, objective-c


If you just released it, object would still point to the memory address that it had before. If you checked it to be nil (object == nil) it would return NO. It is better to make sure that it points to nil after you release it.


This mostly has to do with multi threading, if an other thread tries to access the object you released and set to nil it will not crash. You can send message to nil object and it will just do nothing.

But if it is just deallocated you are sending a message to the deallocated object and your app will crash.

Here is nice reading material:

  • http://iphonedevelopment.blogspot.com/2010/09/dealloc.html
  • http://www.red-sweater.com/blog/1423/dont-coddle-your-code
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜