@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!
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With