Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

objective c - self.prop=nil; vs. [prop release];prop=nil;

If I am using synthesized properties, then why wouldn't I simply say :

self.property = nil;

This will release the ref count, and make sure I don't have a dangling pointer.

Seems straightforward, and yet 99% of code I see seems to do it this way:

[property release];
property = nil;

and yes, in most cases they are properties. I get the horrible feeling I am missing something? Sorta like when I forgot to put "self." in front of some of the properties and wondered why it was crashing :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're trying to clear the value of a property anywhere but in a dealloc method, then self.property = nil; is the best way to do it. It'll handle all the memory management tasks for you, helping to prevent any issues.

If you are in the dealloc method, than the best way to release that ivar is up for debate, but [property release]; tends to be recommended, since calling self.property may have secondary effects. In the dealloc method, calling property = nil; is not necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...