Beginning iOS Development

Course No. 10-152-143

Chapter 29 — init (Obj-C)

Writing init methods

  • The first thing to note about init methods is that they are not constructors like other OO languages have. They are just methods. We use them to create objects, but we have to call them, they are not called automatically. Objective-C does not have constructors.
  • The init method initializes an object. It sets it up for use. The alloc method creates the memory for the object. The init method creates all the variables inside it.

A basic init method

  • An init method always starts the same way
  • You need to call the init method of the superclass before anything else.
  • At the end of every init method you need to return the pointer to this new object.
  • What we do in between is set up all the default values we want our object to have.
  • We need to check that the superclass worked so we always use an if.

init methods that take arguments

  • Since initializers are just methods, we can make them however we want.