I have a +initialize method that is called several times and I donโt understand why.
According to the documentation, it will be called once for each class (and subclasses),
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 another code, but the corresponding part).
No subclasses of MyClass . He does not do anything. Initialization + is called once when my application starts (the NSApplication delegate tells him to populate myStaticArray with data from disk). And then + initialize is called a second time when the user selects a menu item related to this class.
I just added dispatch_once() around my initialize code, and this obviously fixes my problem. But I do not understand what is happening? Why is this called more than once when there are no subclasses?
This is the stack trace on the first call + initialization:
+[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 start the second call + initialize (nothing in the stack trace). This happens immediately after the window is displayed, in which the contents of the static array are cleared +initialize (the window displays the contents of the array, but immediately after that the array is empty).
objective-c cocoa
Abhi Beckert Jan 01 '13 at 12:21 2013-01-01 12:21
source share