Marc Lamberti
Marc Lamberti

Reputation: 821

Init and init with parameters

Here is the code :

@implementation Accumulateur

    // Constructor
    - (id) init
    {
        return ([self initWithTotal:0]);
    }

    - (id) initWithTotal:(int)aTotal
    {
        AccumulateurMoyen   *ac;

        if ((ac = [[AccumulateurMoyen alloc] init]) == nil)
        {
            [self release];
            return (nil);
        }
        return ([self initWithTotal:aTotal andAccumulateurMoyen:ac]);
    }

    - (id) initWithTotal:(int)aTotal 
    andAccumulateurMoyen:(AccumulateurMoyen *)aAcMoyen
    {
        if (self = [super init])
        {
            [aAcMoyen retain];
            [acMoyen release];
            acMoyen = aAcMoyen;
            total = aTotal;
        }
        return (self);
    }
@end

The problem is here : if ((ac = [[AccumulateurMoyen alloc] init]) == nil) As I redefined init, the init called is mine and not that of NSObject... I dont have idea, how i can do that correctly (AccumulateurMoyen is subclass of Accumulateur)

Thx you

Upvotes: 0

Views: 184

Answers (2)

mity
mity

Reputation: 2349

You have probably undesired recursion there: [[AccumulateurMoyen alloc] init] tries to create new AccumulateurMoyen but that results in nested initWithTotal: which again tries to create another AccumulateurMoyen instance etc.

I.e. your code tries to create Accumulateur which has member acMoyen set to new instance of AccumulateurMoyen, which again has its acMoyen set to another new instance of AccumulateurMoyen etc.

You must to break the endless recursion. E.g. in initWithTotal:, replace the line

if ((ac = [[AccumulateurMoyen alloc] init]) == nil)

with

if ((ac = [[AccumulateurMoyen alloc] initWithTotal:0 andAccumulateurMoyen:nil]) == nil)

I.e. the nested AccumulateurMoyen will have its member set to nil.

Upvotes: 1

ggrana
ggrana

Reputation: 2345

Sorry but I think you have a structural problem here. Why your super class need to have an reference to a class that extend it? I think your best option to it is think again how your class structure will be.

But in your subClass you can change the init method to so your problem will disappear.

(id)init {
    return ([NSObject init]);
}

Upvotes: 0

Related Questions