Why does NSString save score 2?

#define kTestingURL @"192.168.42.179" ... NSString *serverUrl = [[NSString alloc] initWithString: [NSString stringWithFormat:@"http://%@", kTestingURL]]; NSLog(@"retain count: %d",[serverUrl retainCount]); 

Why is account deduction 2, not 1?

+4
source share
4 answers

Yes, you get a hold on Count 2, one for alloc and another for stringWithFormat. stringWithFormat is a factory class with auto-advertising, but an auto-abstract reduces the number of accounts in the future.

+5
source

You do not care about the absolute value of the retention account. It's pointless.

He said that we’ll see what happens to this particular case. I slightly modified the code and used a temporary variable to store the object returned by stringWithFormat to make it more understandable:

 NSString *temp = [NSString stringWithFormat:@"http://%@", kTestingURL]; // stringWithFormat: returns an object you do not own, probably autoreleased NSLog(@"%p retain count: %d", temp, [temp retainCount]); // prints +1. Even if its autoreleased, its retain count won't be decreased // until the autorelease pool is drained and when it reaches 0 it will be // immediately deallocated so don't expect a retain count of 0 just because // it autoreleased. NSString *serverUrl = [[NSString alloc] initWithString:temp]; // initWithString, as it turns out, returns a different object than the one // that received the message, concretely it retains and returns its argument // to exploit the fact that NSStrings are immutable. NSLog(@"%p retain count: %d", serverUrl, [serverUrl retainCount]); // prints +2. temp and serverUrl addresses are the same. 
+5
source

You created a row and then used it to create another row. Instead, do the following:

 NSString *SERVER_URL = [NSString stringWithFormat:@"http://%@", kTestingURL]; 
+2
source

this is because you [[alloc] init] is the first NSString, therefore serverUrl is saved +1 and on the same line you call [NSString stringWithFormat] which return another nsstring to autorelease with saving count at 2 you should use only:

NSString * serverUrl = [NSString stringWithFormat: @ "http: //% @", kTestingURL];

so your serverUrl will have keepCount at 1 and you don't need to issue a line

+1
source

All Articles