johnbakers
johnbakers

Reputation: 24770

Should I call super in +initialize?

Do I need to do this:

+(void)initialize{
     ...my stuff...
  [super initialize];
 }

That is to say, if I am over-riding initialize from the parent class (NSObject) in my App Delegate, to I need to make sure the super implementation also gets called? Or does that not apply since this is not an instance method?

Just how "safe" is this method? I'm implementing the iNotify library and the documentation suggests adding the setup to this method, but I've not previously used it for anything in the app, and want to know also if it can potentially conflict with something else unexpectedly?

Upvotes: 8

Views: 2546

Answers (2)

hfossli
hfossli

Reputation: 22962

The runtime sends initialize to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program. The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses. The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize]. If you want to protect yourself from being run multiple times, you can structure your implementation along these lines:

https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/nsobject_class/reference/reference.html#//apple_ref/occ/clm/NSObject/initialize

Thus making both

+ (void)initialize
{
    ...
}

and

+ (void)initialize
{
    [super initialize];

    ...
}

valid.

Upvotes: 0

Denis Mikhaylov
Denis Mikhaylov

Reputation: 2045

if you have subclasses of this class you better call your code using dispatch_once statement because each sublcass will call this method again

+(void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
    {
        //Your Code
    });
}

See this blog post by Mike Ash for details.

Upvotes: 7

Related Questions