views:

603

answers:

2

Hi, I have got a problem with NSString.

NSString* str = [[NSString alloc] initWithString:@"Hello world"];

In the code above, do I need to release the object str? According to the rule, this object is created with alloc, so it should be explicitly released with the release method. However, I can't find any memory leaks in Instruments when I don't explicitly release it. When the NSString is replaced with NSNumber, the memory leaks happen.

Can anyone give me some suggestions? Thanks.

+5  A: 

Yes, you do need to release it. Tools such as Instruments, Leaks, ObjectAlloc and friends aren't infallible; also because you've used a constant string to create the instance it is entirely likely that no leak occurs. But nonetheless, if you +alloc an object you should also -release it to make sure that the object doesn't leak, so you do indeed need to release this object.

My usual set of links to Cocoa memory management articles: http://iamleeg.blogspot.com/2008/12/cocoa-memory-management.html

Graham Lee
+3  A: 

What you're seeing is probably an implementation detail. I suspect -[NSString initWithString:] with an immutable string for an argument just retains its argument and returns it. For constant strings like @"Hello world", they hang around for the life of the program, so retain and release don't do anything.

But you don't need to pay attention to any of that. Cocoa just guarantees that if you follow the memory management guidelines, your memory will be managed properly. Exactly how it works behind the scenes isn't normally something you should be concerned with — just whether you're following the rules.

Chuck
Put another way: Follow the rules and your app will not leak (barring a bug somewhere). Don't follow the rules and your app will leak—someday, if not now.
Peter Hosey