3

I've recently studied some Cocoa based open source projects. I saw that a lot of programs have all initializing code in awakeFromNib and rarely use the designated initializer. I am used to do it that way:

  • in the overridden designated initializer: do all non-Nib stuff
  • in awakeFromNib: do all Nib-related stuff

Is this approach wrong?

1 Answers1

2

Yes, it's correct, all nib-related stuff should be done in awakeFromNib method. At the moment when it's called you already have initialized and loaded view from nib, so you already may configure and use it.

As concerned to initializers, please, check this question: iOS: UIView subclass init or initWithFrame:?

The designated initializer is the one that all the other initializers must call. UIView and subclasses are a little unusual in that they've actually got two such initializers: -initWithFrame: and -initWithCoder:, depending on how the view is created. You should override -initWithFrame: if you're instantiating the view in code, and -initWithCoder: if you're loading it from a nib. Or, you could put your code in third method and override both those initializers such that they call your third method. In fact, that's often the recommended strategy.

Community
  • 1
  • 1
Alexander Tkachenko
  • 3,221
  • 1
  • 33
  • 47