0

Possible Duplicate:
Why should I call self=[super init]

I been reading a book of Objective C, and to create a class that contains other classes (composition) it uses the self = [super init]

- (id) init
{
    if (self = [super init]) {
        engine = [Engine new];

        tires[0] = [Tire new];
        tires[1] = [Tire new];
        tires[2] = [Tire new];
        tires[3] = [Tire new];
    }

    return (self);

} // init

And when he is creating another classes he doesn't include this init method, i understand that it need to initialize the instance objects it will be using, but i don't understand why is he putting the self = [super init] and when a class needs this statement.

@interface Tire : NSObject
@end // Tire


@implementation Tire

- (NSString *) description
{
    return (@"I am a tire. I last a while");
} // description

@end // Tire
Community
  • 1
  • 1
Pedro
  • 41
  • 9
  • Can you include an example of the other classes where this method is not used? It will be easier to explain then. – jrturton Aug 01 '12 at 07:31
  • like Tire class, it only needs the new message or alloc]init] to start, but why this class init method need self = [super init] – Pedro Aug 01 '12 at 07:35
  • 1
    possible duplicate of [Why should I call self=\[super init\]?](http://stackoverflow.com/q/2956943/), [Why use self=\[super init\] instead of just \[super init\]?](http://stackoverflow.com/q/10139765/), [Why to use \[super init\] in constructors](http://stackoverflow.com/q/9283004/), [self=\[super init\] revisited](http://stackoverflow.com/q/9554249/), [self=\[super init\]](http://stackoverflow.com/q/10779937/), [What does the assignment of self to \[super init\] do?](http://stackoverflow.com/q/5594139/) – jscs Aug 01 '12 at 07:49
  • @JoshCaswell possibly, but I think the question was really about the difference between alloc/init and new. – jrturton Aug 01 '12 at 07:56

1 Answers1

0

new is a class method that simply tells a class to perform alloc / init on itself. It is documented here. The code above could be rewritten as:

- (id) init 
{ 
    if (self = [super init]) { 
        engine = [[Engine alloc] init]; 

        tires[0] = [[Tire alloc] init]; 
        tires[1] = [[Tire alloc] init]; 
        tires[2] = [[Tire alloc] init]; 
        tires[3] = [[Tire alloc] init]; 
    } 

    return (self); 

} 

And it would have exactly the same effect, but involves more typing.

Within the Engine and Tire classes, their init methods (if implemented) will be using self = [super init]. If your class does not do anything special in its init method, you don't need to implement one, but if you do implement one, you must use self = [super init] because you need the object to be created properly, and your superclass may be doing important work in its init method.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • thanks man you're explanation was very clear, i really was confuse about this statement, but now i get it =) – Pedro Aug 01 '12 at 15:06