JohnBigs
JohnBigs

Reputation: 2811

Getting error trying to override init method

I have a Square class i'm trying to override an init method, the .m looks like this:

@implementation Square

{
    Rectangle *rect;
}

@synthesize side;

-(int) area
{
    return side * side;
}

-(int) peremiter
{
    return side * 4;
}

-(id) init
{
    return [self init];
}

-(Square *) initWithSide:(int)s
{
    self = [super init];

    if (self)
     [self initWithSide:s];

    return self;
}

@end

The error im getting is in the initWithSide methode that say:

The result of a delegate init must be immediately returned or assigned to self

Upvotes: 0

Views: 119

Answers (3)

holex
holex

Reputation: 24041

drop off your current init methods and replace them with these (don't forget to update them at the interface scope):

- (id)init {
    if (self = [super init]) {
        // do whatever you like to to do here
    }
    return self;
}

- (id)initWithSide:(int)s { // but an NSInteger would be more elegant, and the parameter name 's' also would be better to be like 'side'
    if (self = [super init]) {
        [self setSide:s];
    }
    return self;
}

Upvotes: 1

Tito Q.
Tito Q.

Reputation: 211

This is the correct syntax:

- (id) initWithSide:(int)s{
   self = [super init];
    if (self){
        //init elements 
    }
    return self;
}

Upvotes: 0

Perception
Perception

Reputation: 80603

These lines:

if (self)
 [self initWithSide:s];

Make no sense, and basically means you will call the initializer over and over again. You should change it to do something useful (like set the value of s, for example). On a side note, your no-arg init method is also wrong. It should be:

-(id) init {
    return [super init];
}

But since there is no specialized implementation in it, you don't actually even need it at all.

Upvotes: 2

Related Questions