Man of One Way
Man of One Way

Reputation: 3980

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?

Upvotes: 4

Views: 913

Answers (4)

albertamg
albertamg

Reputation: 28572

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.

Upvotes: 5

Antonin Lacombe
Antonin Lacombe

Reputation: 93

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

Upvotes: 1

iCoder4777
iCoder4777

Reputation: 1692

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.

Upvotes: 5

Peter DeWeese
Peter DeWeese

Reputation: 18343

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

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

Upvotes: 2

Related Questions