In UIViewController subclasses, I often see:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Home", nil);
}
return self;
}
Why not set
self.titlein-viewDidLoad?Are all string literals always loaded into memory?
String literals are compiled into your executable file - they are not resources. They are kept in the initialized static data section in the executable. So yes, on the most basic level they are in memory whenever the executable is loaded - that is, whenever the program is running.
There is paging though. Somtetimes, when the memory runs low, it's possible that the system throws parts of your running executable out of memory to free up some, and reloads them once they're needed. This process is automatic, transparent, and unpredictable. So there's a minor chance that the string is not physically in memory at some point in time, but once you try to access it, it will magically be there. Any paging is never done on per-string basis - it's done in units of 4-8 KB ("pages").
In general, string literals are part of the data section in the compiled Mach-O file. Since all of the code is loaded "into memory" when being executed, that means that the string literals are always loaded into memory as well. This being said, it is still a good idea to retain/release strings just as you would other objects, even if you know that they are going to be literals.
In the example you provided, the NSLocalizedString call is being used for Internationalization. This has nothing to do (memory wise) with the string that you are supplying.
来源:https://stackoverflow.com/questions/7296739/objective-c-are-all-string-literals-always-loaded-into-memory