Over-issuance of the object and application 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]; 

Release line by line:

Line 2: save counter testString = 2
Line 3: save counter testString = 3
Line 4: save counter testString = 1
Line 5: save counter testString = 0
Line 6: it should fall

Even if there is another element in testString that is contained in testString , it will eventually disappear. But the application never crashes because of this.

Can anyone explain this? Thanks!

+4
source share
3 answers

I am not an expert on this, so please take this with salt. I think that [NSString stringWithString:@"a"] will probably just return the literal string @"a" , i.e. Just return your argument. Since @"a" is a literal, it is probably in read-only memory and cannot be freed (therefore, it must be initialized with a very high count value).

+4
source

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"]; does not create a new line, it uses the string literal @ "a". And string literals cannot be freed.

Try using the NSMutableString code and you will see a failure.

+5
source

[NSString stringWithString:@"a"] returns an object with auto-implementation. This means that the โ€œtrueโ€ save count is 2, not 1 on line 4. On line 6, you overfulfill your variable, but the accident will happen later - when the auto-advertisement pool leaks.

0
source

Source: https://habr.com/ru/post/1402871/


All Articles