On Mon, Mar 16, 2009 at 10:21 PM, Steve Cronin <steve_cro...@mac.com> wrote: > > I use an object in my application called 'appDelegate'; it's a subclass of NSObject. > > I instantiate this object in the main Nib file > This object has IBActions for the main menu and since it is -app delegate it is a kind on central dispatcher. > > My question is this: > The +initialize is run twice when the app loads: > 2009-03-16 20:21:42.690 XYZ[6676:813] *[AppDelegate initialize] > 2009-03-16 20:21:42.781 XYZ[6676:813] *[NSKVONotifying_AppDelegate initialize] > > Once for the object itself and then again as the instance in the Nib. That's how I read this. Is that wrong?
Not entirely, but not entirely right either. The +initialize message is sent once to each subclass too, and that's what is happening here. When you use Cocoa Bindings, the bindings machinery replaces the isa variable in your AppDelegate instance with one that refers to a subclass of AppDelegate that's created at run time - that's the NSKVONotifying_AppDelegate class mentioned above. So it's not your AppDelegate class that's getting sent a second +initialize message, it's the NSKVONotifying_AppDelegate being sent its first (and only) +initialize message. Since that class doesn't implement its own +initialize, then naturally the message is routed to its parent class instead - the +initialize implementaion in your AppDelegate class. The obscure part of this is that KVO is creating a subclass for you, and it's the subclass' +initialize that you're actually seeing. Once you understand the situation, the solution to it easy - it's right there in the docs for the method: If a particular class does not implement initialize, the initialize method of its superclass is invoked twice, once for the superclass and once for the non-implementing subclass. If you want to make sure that your class performs class-specific initializations only once, implement initialize as in the following example: @implementation MyClass + (void)initialize { if ( self == [MyClass class] ) { /* put initialization code here */ } } Incidentally, does anyone else find this behavior rather odd? I'd expect KVO to create +initialize methods automagically, to avoid this kind of confusion. :-( sherm-- -- Cocoa programming in Perl: http://camelbones.sourceforge.net _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com