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?
From Is a literal NSString autoreleased or does it need to be released?
Under the hood when you do
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
retainorcopy.On the contary when you do
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.