2

In this code I am loading a View Controller (and associated View) from a .xib:

-(id)initWithCoder:(NSCoder *)coder
    {
    // add custom initialisation code here
    [super initWithCoder:coder];
    return self;
    }

This successfully works, but I do not really understand what the line [super initWithCoder:coder] is accomplishing. Is that initializing my View Controller after my View has been initialized?

Please be as explicit as possible when explaining. Thanks.

1
  • 1
    Just for the record, if you're new to this stuff. (1) SOMETIMES (not always) you happen to want to add something to the "setup" of a class, when it is launched. (2) IF you happen to need to do that, the WAY you do it is with code exactly like the above. Note however that, (3) the code above actually does absolutely nothing. In fact, very simply, it is nothing more than an EXAMPLE of WHAT YOU WOULD DO for this particular type of class, if, you needed to "add set up code" to the class in question. (In fact, you'd "add your new setup code just before line 3".) Makes sense?! :) Commented Mar 9, 2014 at 14:27

1 Answer 1

4

Your class is a subclass of UIViewController. The call is telling your super class (UIViewController) to do the steps it needs to accomplish so that you can do your init steps. This would be setting up any properties that the UIViewController provides or registering for notifications that the UIViewController needs to do its work.

It is suggested almost every time you override a method from the super class to call the super class's method in addition to the steps you need to take.

Edit: Also if you don't need to do anything in a method the superclass provides, you can just leave it out and the super class's method will be used instead. In this case I would not provide the initWithCoder: method unless there was some code you need to preform in addition to what you showed.

Sign up to request clarification or add additional context in comments.

3 Comments

Just to be clear, Interface Builder is automatically subclassing my UIView class from UIViewController when I add a UIView object to the UIViewController.xib? I do see that if I exclude initWithCoder from my UIView custom class everything also loads normally, that was a useful tip.
An instance of a UIView subclass will only be created if the the UI View object in the .xib is configured with the subclass name in the Identity Inspector in IB (under Custom Class).
Lucas - lol thanks good one :) (bold is easy to misinterpret right! :) )

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.