简体   繁体   中英

Why is NSString retain count 2?

#define kTestingURL @"192.168.42.179"

...

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

Why is the retain count 2 and not 1?

Yes, You will get retain Count 2, one for alloc and other for stringWithFormat. stringWithFormat is a factory class with autorelease but autorelease decreases retain count in the future.

You shoud not care about the absolute value of the retain count. It is meaningless.

Said that, let's see what happens with this particular case. I slightly modified the code and used a temporary variable to hold the object returned by stringWithFormat to make it clearer:

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's 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.

You created a string and then used it to create another string. Instead, do this:

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

this is because you [[alloc] init] a first NSString so serverUrl have retain +1 and at the same line you call [NSString stringWithFormat] that return another nsstring on autorelease with retain count at 2 you should only use the :

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

so your serverUrl will have retainCount to 1 and you don't have to release string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM