Objective-C: Are all string literals always loaded into memory?

淺唱寂寞╮ 提交于 2019-12-07 17:45:49

问题


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;
}
  1. Why not set self.title in -viewDidLoad?

  2. Are all string literals always loaded into memory?


回答1:


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").




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!