Sunday, May 1, 2011

Why don't I have to release these objects?

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

From stackoverflow
  • 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.

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

    paxdiablo : You need either two more 'f' characters in that hex value, or the decimal should be 2^23 - 1, not 2^31 - 1.
    htw : Thanks—I made a typo when typing that hex value out. Lost track of how many bytes I had written. Sorry about that—fixed.
    Ahruman : 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.
    htw : Yup, I checked the documentation again, and you are indeed correct. Fixed.

0 comments:

Post a Comment