1

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.

2
  • Am I right in thinking you just don't do self = [super init] in the subclass init method? Commented Jan 18, 2012 at 16:48
  • I think he is talking about the class initialize method, but if he is really referring to init, then that is correct. Commented Jan 18, 2012 at 16:51

3 Answers 3

7

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

I implement initialize in BOTH my subclass and superclass. According to the apple docs, the superclass's initialize will always get called before any subclasses. Is there anyway to prevent that
Huh. I tested it out and see the same thing. I think I'm changing my answer. What is Foo's initialize method doing that you must prevent?
It alloc-inits an object that listens for and acts on notifications in a way different to how its subclass does it. I've solved it by not implementing initialize and just calling a setup method instead.
Sounds like a reasonable solution.. It probably didn't belong in initialize in the first place. Please add your answer and accept it when allowed.
0

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

2 Comments

Costique's answer is better, and also the recommended way by Apple. Calling a setup method only once can be surprisingly difficult in the presence of multiple threads, and initialize is made for that purpose.
Fishinear, bbum says otherwise and is usually right (friday.com/bbum/2009/09/06/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.