How to initialize an NSObject's subclass on iPhone?

Chilly Zhong picture Chilly Zhong · Mar 2, 2009 · Viewed 23.4k times · Source

I want to write some methods in a class so that other classes can call these methods using [instance methodName:Parameter].

If the class is a subclass of UIViewController, I can use initWithNibName to initialize it. But I want to write the methods in an NSObject's subclass, how can I initialize it?

Answer

Jane Sales picture Jane Sales · Mar 2, 2009

iphony is correct, but he or she doesn't say that you need to write the init method yourself. Your init method should generally look something like this:

- (id) init
    {
    if (self = [super init])
         {
         myMember1 = 0; // do your own initialisation here
         myMember2 = 0;
         }
    return self;
    }

Although the apple documentation says

The init method defined in the NSObject class does no initialization; it simply returns self.

and one can just be tempted to write

- (id) init
  {
    myMember1 = 0; // do your own initialisation here
    myMember2 = 0;
    return self;
  }

this is WRONG and not following what is explicitly stated in documentation:

In a custom implementation of this (init) method, you must invoke super’s designated initializer then initialize and return the new object.

MUST. Not should, could, ought to, etc.

You should not assume NSObject's init does not change in future; nor the superclass from which your custom class derives.