Objective-C 覆盖 [NSObject 初始化] 是否安全?

Objective-C Is it safe to overwrite [NSObject initialize]?(Objective-C 覆盖 [NSObject 初始化] 是否安全?)

本文介绍了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() {...}

您最好进行初始化以响应正在启动的应用程序.NSApplicationUIApplication 都提供委托/通知挂钩,用于在应用启动时将一些代码注入到应用中.

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 初始化] 是否安全?