Objective-C:所有字符串文字总是加载到内存中吗?

发布于 2024-12-02 17:30:08 字数 444 浏览 1 评论 0原文

UIViewController子类中,我经常看到:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Home", nil);
    }
    return self;
}
  1. 为什么不在-viewDidLoad中设置self.title

  2. 所有字符串文字总是加载到内存中吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荒芜了季节 2024-12-09 17:30:08

一般来说,字符串文字是已编译的 Mach-O 文件中数据部分的一部分。由于所有代码在执行时都会加载“到内存中”,这意味着字符串文字也总是加载到内存中。话虽这么说,就像保留/释放其他对象一样保留/释放字符串仍然是一个好主意,即使您知道它们将是文字。

在您提供的示例中,NSLocalizedString 调用用于国际化。这与您提供的字符串无关(内存方面)。

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.

财迷小姐 2024-12-09 17:30:08

字符串文字被编译到您的可执行文件中 - 它们不是资源。它们保存在可执行文件的初始化静态数据部分中。所以,是的,在最基本的层面上,每当加载可执行文件时(即每当程序运行时)它们都在内存中。

不过有分页。有时,当内存不足时,系统可能会抛出部分正在运行的可执行文件以释放内存,并在需要时重新加载它们。这个过程是自动的、透明的且不可预测的。因此,该字符串在某个时间点物理上并不存在于内存中的可能性很小,但是一旦您尝试访问它,它就会神奇地出现在那里。任何分页都不会按字符串进行 - 它以 4-8 KB(“页”)为单位进行。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文