简体   繁体   中英

Purpose of designated initializers

I am confused about what can be the reasons of writing designated initialisers in objective C. And and calling the superclass's init method so that it overrides it superclass's implementation ?

Can anyone explain what can be the possible reasons for creating such methods?

for example,

 -(id)initWithCardCount:(NSUInteger)count usingDeck:(Deck *)deck // Designated Initialiser
   {
    self = [super init]; 

    if(self)
    {
        for (int i = 0; i < count; i++)
        {
            Card *card = [deck drawRandomCard];

            if(!card)
            {
                self = nil;
            }else
            {
                self.cards[i] = card;

            }

        }
    }
    return self;
}

Most Objective-C objects ultimately descend from NSObject, but the object you're trying to initialize is likely to besubclassed from additional objects. For example, your subclassed FarhanViewController will subclass from UIViewController which subclasses from UIResponder and ultimately NSObject.

Calling " [super init] " within your object's init method allows the base class to initialize whatever else it needs to set in order to do it's job properly.

You also may find some more useful information in this Apple documentation: "Multiple Initializers and the Designated Initializer"

The short version of this is that, without a designated initialiser, I don't know how to subclass your class correctly.

Say you define a Fruit class, and I want to define an Apple .

What should I call in my own init method? Should I call initWithTastiness: ? Just plain init ? I have no idea.

With a designated initialiser, my subclass knows exactly want to do in order to create a new Fruit , and you know that your class will never (validly) be called without initialisation, allowing invariants etc to hold.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM