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 初始化] 是否安全?
基础教程推荐
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01