简体   繁体   中英

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

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM