if I release a variable more than it should be, would that be a problem? I cannot determine the retain count ahead of time.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Foreword
The retain count should be considered more of a theoretical offset. You should never care about what the value currently is, just how your actions will offset it. For example, when you add an object to an array, you have offset its retain count by +1, and when you remove an object from an array, you have offset its retain count by −1. When you’re completely done with an object, its retain count offset (relative to you) should be 0. What its retain count actually is does not matter, as long as you fulfil your obligations to manage the object appropriately.
Inspecting the retain count explicitly will often not show what you expect. This could be because of optimisations under the hood. Cocoa relies on the developer conforming to the memory management guidelines. Follow these very simple rules, and do not worry about the explicit value of
retainCount.WRT the question
Over-releasing an object (sending it too many release messages) can—and usually does—result in premature deallocation of that object. Any messages that get sent to the address where the deallocated object used to be will usually crash your application. The dumbed-down rules of thumb are:
Sending a
alloc,new,retain,copy(or any method withcopyin its name) will give you an object with a retain count offset by +1.Sending
releasewill offset that objects retain count by −1.Balance each +1 with a −1 and that’s it!
Furthermore
If you are developing a framework or library and you are returning objects to users of your framework, don’t try to prevent errors in their code by over-retaining objects. Their obligations are exactly the same as yours, and if they break your framework from poor memory management then that is a bug in their code, not yours.