简体   繁体   中英

When does [[NSMutableData data] retain] is released?

I used to see [[NSMutableData data] retain] instruction in many codes but I don't know when the retained object is released...Can you help me understand ?

Thx in advance,

Stephane

The short answer is: it isn't released until you release it. You've incremented the retain count and, in doing so, you've taken on the responsibility of releasing it later.

A situation you may have seen is one where people are assigning to ivars directly; the release should come in -dealloc —when the containing object is destroyed—or when the ivar is reassigned. But in either case, you must remember to do so, or your code will leak.

It isn't. It leaks.

[NSMutableData data] is already autoreleased--it will be released at the end of the current autorelease pool (ie the end of the current run loop iteration in most cases.) By sending it the -retain message, you're telling it to hang around a bit longer, but without a corresponding -release message, it will never have a retain count of 0 and so will never be deallocated.

[NSMutable data] will not be released till you release it when you add 1 to it's retain count. By using [[NSMutable data] retain] you are adding one to it's retain count and by releasing it you will be decreasing one from it's retain count. So when you are done using it (in the dealloc method) release it.

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