我正在从事的项目存储一些像这样的常量字符串:
(.h)
extern NSURL *kURLLocationComputer;
我需要按如下方式初始化它们:
(.mm)
NSURL *kURLLocationComputer;
... {
kURLLocationComputer = [[NSURL alloc] initWithString:@"computer:///"];
... }
问题是它们在项目中的很多地方都被使用,并且需要首先初始化它们。但由于某些初始化很复杂(不是恒定的),因此它们无法内联完成。
我应该如何确保它们在使用前已初始化?我正在考虑添加一个虚拟类并初始化 +load
中的变量,但我没有认为我们可以假设 Cocoa 库类到那时就可以工作了。
最佳答案
经过一番研究,发现__attribute__((constructor))
函数保证在调用+load
之后被调用所有类(class)。来自关于 +load
的 NSObject 文档:
The
load
message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.The order of initialization is as follows:
- All initializers in any framework you link to.
- All
+load
methods in your image.- All C++ static initializers and C/C++
__attribute__(constructor)
functions in your image.- All initializers in frameworks that link to you.
关于objective-c - 何时何地从任意消息返回值初始化外部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14152376/