Reputation: 1229
Can anybody explain me why does the case1 and case2 crashes while the others does not in case of non-ARC?
Case1:
NSString *rr = [[NSString alloc] initWithString:@"AB"];
[rr release];
[rr autorelease];
Case2:
NSString *rrr = [[NSString alloc] initWithString:@"AB"];
[rrr autorelease];
[rrr release];
Case3:
NSMutableString *rr1 = [[NSMutableString alloc] initWithString:@"AB"];
[rr1 release];
[rr1 autorelease];
Case4:
NSMutableString *rrr1 = [[NSMutableString alloc] initWithString:@"AB"];
[rrr1 autorelease];
[rrr1 release];
Case5:
NSArray *rr3 = [[NSArray alloc] initWithObjects:@"jj", nil];
[rr3 release];
[rr3 autorelease];
Case6:
NSArray *rrr3 = [[NSArray alloc] initWithObjects:@"jj", nil];
[rrr3 autorelease];
[rrr3 release];
Case7:
NSMutableArray *rr2 = [[NSMutableArray alloc] initWithObjects:@"jj", nil];
[rr2 release];
[rr2 autorelease];
Case8:
NSMutableArray *rr2 = [[NSMutableArray alloc] initWithObjects:@"jj", nil];
[rr2 autorelease];
[rr2 release];
Upvotes: 0
Views: 64
Reputation: 112855
All are are incorrect because eventually all will be released twice, but some may coincidentally not crash.
The alloc
allocates the object with a retain count of 1. release
decreases the retain count 1. autorelease
eventually decreases the retain count 1. That means that all are over released.
But as @Chuck mentions some instances are constants, are created at compile time and never released so release
and autorelease
can be called to many tines with no crash.
String constants are one instance of this this where over-releasing will not cause a crash:
NSString *s = @"aa";
Even over-releasing this is OK because the compiler is smart enough:
NSString *s = [NSString stringWithString:@"aa"];
But you will get a warning from the current LLVM compiler that using stringWithString
with a literal is redundant.
Upvotes: 3