Which method is called first when loading the storyboard?

Using Xcode 4.2, in my application, view loading is triggered by the segue event. Which method will be called first inside the view controller?

-(void) viewWillAppear:(BOOL)animated works, but is it the first?

Initialization comes from the Storyboard , it looks like the init method is never called manually when creating the object.

Let me make it clear that when creating an instance of a class manually, we usually [[alloc]init] first. [init] in this case is the first method to be executed, and a good place for various initializations.

What is equivalent to the init method when an instance of a class occurs through a segue event? In that case, which method should contain all the initialization logic?

+4
source share
3 answers

I think the best option is -(void)awakeFromNib . This happens only once, while viewWillAppear and viewDidLoad , etc. May be called more than once after initialization.

UPDATE: As pointed out by Jean-Denis Muys below, -(id)initWithCoder:(NSCoder *)decoder is the best option for an initializer that gets only once when -(void)awakeFromNib has the ability to be called more than once.

+12
source

According to Apple View Controller Programming Guide ,

When you create a view controller in a storyboard, the attributes you configure in Interface Builder are serialized in the archive. Later, when an instance of the view controller is created, this archive is loaded into memory and processed. The result is a set of objects whose attributes correspond to those that you set in Interface Builder. The archive is loaded with a call to the dispatcher method of the form initWithCoder: Then the awakeFromNib method awakeFromNib called for any object that implements this method. This method is used to perform any configuration steps that require other objects to be created.

+5
source

I would advise against using awakeFromNib. I just use both of these functions

 - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self setup]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super initWithCoder:aDecoder]) { [self setup]; } return self; } - (void)setupButton { /* get ready to be called twice */ self.layer.cornerRadious = 10.0f; } 

, because: let's say you subclass UIButton. In this case, you should be prepared for two scenarios :

  • If you add a button programmatically -> initWithFrame-> setupUI can be called
  • If you add a button using NIb -> initWithCoder-> setupUI, it is called.
+1
source

Source: https://habr.com/ru/post/1382518/


All Articles