I have been writing objective c for couple of weeks. However this question still bothers me a lot. Can anyone explain in pain english: When to retain an object?
Thanks
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.
This question has been asked many times before. Take a look at this article that summarizes all of the possible situations.
Basically, you retain the object if you are taking control of it. So let’s say you got a string using
NSString‘sstringWithFormat. According to the article above, this type of method would return anautoreleaseresult. If you were to use this result for a longer period, say, longer than the scope in which it is received, then you will want toretainit to signify that you will be ‘taking control’ of this result. Otherwise, it wouldreleaseitself (hint: autorelease) thinking no one no longer needs it.If you read the article, you’ll see what to do in what cases (it’s pretty specific and concise). Knowing this, you then make your decision based on whether or not you will be needing an object longer than expected.
If you use properties, with the
retainattribute, then this would be taken care of for you automatically. Using the above example:The result would automatically be retained because you are using the property.