views:

209

answers:

2

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...?

+6  A: 

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.

zPesk
+4  A: 

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.

htw
You need either two more 'f' characters in that hex value, or the decimal should be 2^23 - 1, not 2^31 - 1.
paxdiablo
Thanks—I made a typo when typing that hex value out. Lost track of how many bytes I had written. Sorry about that—fixed.
htw
The string isn’t “automatically added to the release pool”. Constant string objects are never deallocated, and releasing or autoreleasing them has no effect. On the other hand, only one instance of the string (per source file) exists.
Ahruman
Yup, I checked the documentation again, and you are indeed correct. Fixed.
htw