本文介绍了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初始化]是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:59