Do you know what happens 开发者_开发知识库if I retain an autoreleased object ? Will it be released or does the retain wins ?
Do you know what happens if I retain an autoreleased object ? Will it be released or does the retain wins ?
The retain
"wins" but thinking of it that way is full of fail.
retain and release are merely mechanisms via which you increase or decrease the retain count of an object. Autorelease is simply a delayed release; no more, no less.
If you retain an autoreleased object you are increasing the retain count NOW while the retain count will be decreased LATER. This happens all the time; [NSString stringWithFormat: @"...."]
returns an autoreleased string that you retain
if you want it to stick around beyond [most typically] the current pass through the event loop.
If you want to keep your variable around, you need to retain it. For example:
myButton = [[UIButton buttonWithType:...] retain];
The buttonWithType:
method returns a UIButton
that's been instantiated with autorelease
. It'll take care of releasing itself (so to speak) when needed.
The retain will win out. This is very common, and is an excepted practice.
Usually convenience methods return autoreleased objects like
[NSString stringWithFormat:@""];
It is expected that you retain whatever objects you need to, so long as you remember to release them later.
Remember that autoreleases will happen at the end of the current system message.
From the article below: "an autorelease pool is created for each message that is processed by the system and the objects in the pool are all automatically released after processing on that message has completed."
Some great explanations of this can be found here:
http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/7295-getters-setters-properties-newbie.html
精彩评论