How Objective-C handles the memory of immutable st

2019-07-28 03:43发布

问题:

This question already has an answer here:

  • Do I need to release a constant NSString? 2 answers

In my research I've come across something peculiar.

@interface Class {
    NSString *_string
}

- (void) Method1 {
    _string = @"ASDF";
}

Intially I thought that _string was part of the autorelease pools and really didn't think about the memory aspect of it.

After reading this SO post Objective C NSString* property retain count oddity I've realized that no, this is not the case, and that the retain count of _string is actually UINT_MAX

Obviously my thinking that _string was part of the autorelease pool was a fluke, and how I handled the variable just somehow worked out. What I would like to know, though, is: when does @"ASDF" get thrown away? I know I should be using properties and setters, but there is probably a lot of code out there that looks like this since assigning a constant to a variable is so intuitive.

What is the lifecycle of these immutable, literal NSStrings, and when will [_string length] actually return an error since @"ASDF" doesn't reside in memory anymore?

回答1:

From Is a literal NSString autoreleased or does it need to be released?

Compiler allocated strings (of the format @"STRING") are constant, and so -retain, -release, and -autorelease messages to them are ignored. You don't have to release or autorelease foo in this case (but it won't hurt).

Under the hood when you do

NSString* yourString = @"ABC";

the string will be stored in a area of memory called data segment. This area never changes after the application is launched. Here strings are treated as constants for your app. At the same time a string is an object, so if you want to keep it you call retain or copy.

On the contary when you do

NSString* yourString = // alloc-init

you create an object on the heap. If you forget to release you have a memory leak. If someone else destroy it, and you try to access it, you have a bad access to that memory location.

Hope that helps.



回答2:

An immutable string (NSString) that is created manually follows the normal reference counting rules and thus life cycle.

In your example, the string is even more special because it is actually a string literal. As is the case for any literal, they reside in special memory and only get destroyed when the executable terminates.