简体   繁体   English

释放或释放目标c中的最佳实践?

[英]dealloc or releasing best practice in objective-c?

I just simply release objects as such: 我只是简单地释放对象:

[myObj release];

I have seen others add: 我看到其他人补充说:

[myObj release]; myObj = nil;

Is the latter more advantageous because now there will never be a reference to that pointer? 后者是否更有利,因为现在将永远不会引用该指针?

It is just to make sure that other successive messages that might be send to myObj don't throw an exceptions. 只是要确保可能发送给myObj其他连续消息不会引发异常。 Message send to nil are possible in Objective-C. 在Objective-C中可以将消息发送到nil

Otherwise, myObj still points to the memory address where it has been and accessing it might result in a BAD_ACCESS error. 否则, myObj仍将指向其到达的内存地址,访问它可能会导致BAD_ACCESS错误。

According to me this is purely depend on the scope of myObject. 据我说,这完全取决于myObject的范围。

  1. If myObject scope is getting ended with the release statement then there is no advantage in setting it to nil 如果myObject范围以release语句结束,则将其设置为nil没有任何好处。

  2. If myObject scope don't end with release statement then setting the object to nil make your object access safe. 如果myObject范围未以release语句结尾,则将对象设置为nil可使对象访问安全。 There is good chance that myObject memory is released and you try to access this memory location which will lead to exception. myObject内存很有可能被释放,并且您尝试访问此内存位置,这将导致异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM