I have a +initialize
method that is being called multiple times, and I don't understand why.
According to the documentation, it will be called once for every class (and subclasses as well),
This is the code I'm using:
@interface MyClass : NSObject
@end
static NSArray *myStaticArray;
@implementation MyClass
+ (void)initialize
{
myStaticArray = [NSArray array];
}
@end
(obviously there is other code, but that's the relevant part).
There are no subclasses of MyClass
. It doesn't do anything fancy. The +initialize gets called once, when my application is launched (NSApplication's delegate tells it to fill myStaticArray with data from the disk). And then +initialize is called a second time, the first time a user selects a menu item that relates to this class.
I've simply added dispatch_once()
around my initialize
code and this obviously fixes my problem. But I don't understand what is going on? Why is it called more than once when there are no subclasses?
This is the stack trace the first time +initialize is called:
+[MyClass initialize]
_class_initialize
objc_msgSend
-[MyAppDelegate applicationDidBecomeActive:]
_CFXNotificationPost
NSApplicationMain
main
start
And here is the second call:
+[MyClass initialize]
_class_initialize
NSApplicationMain
main
start
As you can see, my code does not appear to trigger the second call to +initialize (nothing in the stack trace). It occurs immediately after I display a window that presents the contents of the static array cleared by +initialize
(the window shows the array contents, but immediately after that the array is empty).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…