Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

initialization - Objective-C Is it safe to overwrite [NSObject initialize]?

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

I was wondering: Is it safe for me to have a category that overrides the NSObject's +initialize method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 has more predictable and well-defined behavior, but happens too early to do anything useful because so many things are in an uninitialized state.

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() {...}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...