tags:

views:

42

answers:

2

When I create a NSString with initWithFormat , I get an retain count of 1

-(NSString *)description
{
 NSString *descr = [[NSString alloc]
 initWithFormat:@"I am the description."];

 NSLog(@"Count: %lu",[descr retainCount]);

 return [descr autorelease];
}

If I use initWithString instead I get a count of 2147483647

NSString *descr = [[NSString alloc]
initWithString:@"I am the description."];

So there must be a difference between these two methods in terms of memory management. What is happening here?

+4  A: 

First of all, you shouldn't care what the retain count is, only whether you're properly balancing your -init, -copy and -retain messages with -release or -autorelease messages.

That being said, when you create an NSString instance by parsing a format string, memory is allocated for it. When you create a string by referencing a constant string in your code, you end up with a pointer to that constant string, and its retain count will typically show up as UINT_MAX. That's an implementation detail that you don't need to worry about.

NSResponder
A: 

@NSResponder /and the rest of the world/: no, don’t balance init, copy and retain. NARC is the question, balance new…, alloc…, retain… and copy… messages is the answer!

Greetings

Objective Interested Person