Objective-c – Memory issue of NSString

cocoaobjective c

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.

Best Answer

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

Related Topic