Reputation: 40329
Here's an sample code, where only the "string" object is released.
NSString *nameOfFile = ... ;
NSError *error;
NSString *string = [[NSString alloc] initWithContentsOfFile:nameOfFile encoding:NSUTF8StringEncoding error:&error];
if (string == nil) {
// handle error
}
[string release];
I understand why the error object is not released. This is, since the method here did not create that error object with an "new" or "alloc" method. Instead, this one is returned by reference, so the initWithContentsOfFile method is responsible for that memory. But what about the nameOfFile object? Why don't they release it? It's not returned by reference...?
Upvotes: 2
Views: 397
Reputation: 15750
Assuming nameOfFile
is a constant string, then it automatically has a retain count of 7fffffff
(i.e. 2147483647
, the highest possible retain count). Basically, string literals last for the duration of execution and are never deallocated, so you should never worry about releasing them.
Remember, you only need to release an object if you have either retained it or explicitly allocated memory for it.
See Apple's documentation for more information.
Upvotes: 4
Reputation: 4353
similar to why you do not need to release error
, you also do not need to release nameOfFile
. In Objective-C if you declare a string as NSString *temp = @"Hello"
it is treated as a string constant and it does not need to be released. The memory reference count is zero so it does not need to be released.
Upvotes: 6