Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Over-release an object and the app does not crash

@property (retain) NSString *testString;
self.testString = [[NSString alloc] initWithString:@"aaa"];
[self.testString retain];    
self.testString = [NSString stringWithString:@"a"];
[self.testString release];
[self.testString release];

Let's go line by line:

Line 2: retain count of testString = 2
Line 3: retain count of testString = 3
Line 4: retain count of testString = 1
Line 5: retain count of testString = 0
Line 6: it should crash

Even if there's other stuff holding to testString in CoreFoundation, it eventually will go away. But the app never crash due to this.

Anyone could explain this? Thanks!

like image 939
jasondinh Avatar asked Jan 17 '23 03:01

jasondinh


2 Answers

see this code and its log:

NSString *string1 = [NSString stringWithString:@"a"];
NSString *string2= @"a";
NSLog(@"String1: %p", string1);
NSLog(@"String2: %p", string2);

2012-03-22 13:21:49.433 TableDemo[37385:f803] String1: 0x5860
2012-03-22 13:21:49.434 TableDemo[37385:f803] String2: 0x5860

as you see [NSString stringWithString:@"a"]; doesn't create a new string, it uses the string literal @"a". And string literals can't be deallocated.

Try your code with NSMutableString and you will see a crash.

like image 179
Matthias Bauch Avatar answered Jan 28 '23 00:01

Matthias Bauch


I am not an expert about this, so please take this with a grain of salt. I guess that [NSString stringWithString:@"a"] will probably just return the literal string @"a", i.e. it just returns its argument. As @"a" is a literal, it probably resides in constant memory and can't be deallocated (so it should be initialized with a very high retain count).

like image 45
MrMage Avatar answered Jan 27 '23 22:01

MrMage