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:
- There is a class
O
. It contains no variables and does nothing. - There is a class Count. It initializes
O
and increments, decrements counts for it - There is a UI nib with 2 buttons: Retain and Release
- (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
- We start off with a retain count of 1, after alloc init sequence
- Followed by manual retain count goes up to 2
- We then decrease the count and it goes down to 1
- After which next decrease ..... seemingly does nothing Retain count is still 1
- This release refers to bad memory and crashes the app.
Please help me understand this behavior