简体   繁体   中英

When to retain in objective C?

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

Check out Apple's website on memory management and object ownership.

http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html

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 's stringWithFormat . According to the article above, this type of method would return an autorelease result. 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 to retain it to signify that you will be 'taking control' of this result. Otherwise, it would release itself (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 retain attribute, then this would be taken care of for you automatically. Using the above example:

my.property = [NSString stringWithFormat:@"%f", 0.2f];

The result would automatically be retained because you are using the property.

Plain english, not code? Try this: Objective-C retain counts clarification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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