Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an NSObject's subclass on iPhone?

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?

like image 691
Chilly Zhong Avatar asked Mar 02 '09 13:03

Chilly Zhong


1 Answers

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.

like image 99
Jane Sales Avatar answered Oct 30 '22 20:10

Jane Sales