Possible Duplicate:
check retain count
As i was playing with retain
, release
counts, i ran into a situation, i am not able to explain. Please help me understand it better:
O
. It contains no variables and does nothing.O
and increments, decrements counts for it- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
o = [[O alloc]init]; // At this moment [o retainCount] is 1 as expected
....
For every doRetain, counts increments as expected
- (IBAction)doRetain:(id)sender {
[o retain];
NSString *result = [[NSString alloc] initWithFormat:@"%d", [o retainCount]];
[label setText: result];
[result release];
}
Whenever release is called, count is decreased
- (IBAction)doRelease:(id)sender {
[o release];
NSString *result = [[NSString alloc] initWithFormat:@"%d", [o retainCount]];
[label setText: result];
[result release];
}
Consider 1 retains and 2 releases
Please help me understand this behavior
If your retain count is 1 and you release, the object is no longer valid, and the releaseCount property is meaningless (and the results of which are unpredictable).
Also, I know this is a test, but you create your strings with 'alloc', but never release them.
When working with release and retain, you are only responsible for releasing YOUR OWN retains. Other objects may perform retains on the object in question, and they will, in turn, release them.
If you get an object using a method containing the words alloc
, copy
or create
, there is an implied retain
on said object. Otherwise, you can assume that the object will go away after the current run loop, so if you want to hang onto a copy of the object, you'll need to perform a retain. When you're done with the object, do a release.