JPC
JPC

Reputation: 8296

Subclassing initialize method in objective-c

I have a class Foo that implements an +(void)initialize method. I also have a class that's a subclass of Foo. When I instantiate the subclass, the initialize method also gets called on Foo which I don't want. How do I prevent this?

Thanks.

Upvotes: 1

Views: 965

Answers (3)

JPC
JPC

Reputation: 8296

I've solved it by not implementing initialize and just calling a setup method instead

Upvotes: 0

Costique
Costique

Reputation: 23722

In your scenario (when there are subclasses involved) you should check the class to which the initialize method is sent:

+ (void) initialize
{
    if ( self == [MyClass class] )
    {
        // Do something here only once
    }
}

Upvotes: 7

Peter DeWeese
Peter DeWeese

Reputation: 18333

You'll need to implement + (void)initialize in your subclass as well. Usually people call [super initialize], but you'll want to skip that step. An empty method will prevent Foo's from being called.

EDIT The superclasses initialize method is always called. It can't and shouldn't be prevented by subclassing, because technically the superclass is initialized too and could be used independently.

Upvotes: 1

Related Questions