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

后端 未结 3 740
悲&欢浪女
悲&欢浪女 2020-12-17 02:55

Basically, I have the following code (explained here: Objective-C Constants in Protocol)

// MyProtocol.m
const NSString *MYPROTOCOL_SIZE;
const NSString *MYP         


        
3条回答
  •  甜味超标
    2020-12-17 03:32

    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.

提交回复
热议问题