简体   繁体   中英

Objective-C : Just another retain count question

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?

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 /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

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