Objective-C Is it safe to overwrite [NSObject initialize]?(Objective-C 覆盖 [NSObject 初始化] 是否安全?)
问题描述
基本上,我有以下代码(此处解释:Objective-C 协议中的常量)
Basically, I have the following code (explained here: Objective-C Constants in Protocol)
// MyProtocol.m
const NSString *MYPROTOCOL_SIZE;
const NSString *MYPROTOCOL_BOUNDS;
@implementation NSObject(initializeConstantVariables)
+(void) initialize {
if (self == [NSObject class])
{
NSString **str = (NSString **)&MYPROTOCOL_SIZE;
*str = [[MyClass someStringLoadedFromAFile] stringByAppendingString:@"size"];
str = (NSString **)&MYPROTOCOL_BOUNDS;
*str = [[MyClass someStringLoadedFromAFile] stringByAppendingString:@"bounds"];
}
}
@end
我想知道:拥有一个覆盖 NSObject 的 +initialize
方法的类别对我来说安全吗?
I was wondering: Is it safe for me to have a category that overrides the NSObject's +initialize
method?
推荐答案
简而言之,不,您不能安全地在类的类别中实现 +initialize
方法.你最终会替换现有的实现,如果有一个,并且如果一个类的两个类别都实现了 +initialize
,则无法保证会执行哪个.
In short, no, you cannot safely implement +initialize
methods in categories on classes. You'll end up replacing an existing implementation, if there is one, and if two categories of one class both implement +initialize
, there is no guarantee which will be executed.
+load
具有更可预测和定义明确的行为,但发生得太早而无法做任何有用的事情,因为很多东西都处于未初始化状态.
+load
has more predictable and well-defined behavior, but happens too early to do anything useful because so many things are in an uninitialized state.
就个人而言,我完全跳过 +load
或 +initialize
并使用编译器注释来使函数在加载底层二进制/dylib 时执行.不过,在那个时候,您可以安全地做的事情很少.
Personally, I skip +load
or +initialize
altogether and use a compiler annotation to cause a function to be executed on load of the underlying binary/dylib. Still, there is very little you can do safely at that time.
__attribute__((constructor))
static void MySuperEarlyInitialization() {...}
您最好进行初始化以响应正在启动的应用程序.NSApplication
和 UIApplication
都提供委托/通知挂钩,用于在应用启动时将一些代码注入到应用中.
You are far better off doing your initialization in response to the application being brought up. NSApplication
and UIApplication
both offer delegate/notification hooks for injecting a bit of code into the app as it launches.
这篇关于Objective-C 覆盖 [NSObject 初始化] 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Objective-C 覆盖 [NSObject 初始化] 是否安全?
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- UITextView 内容插图 2022-01-01
- URL编码Swift iOS 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01