Kordan Ou
Kordan Ou

Reputation: 1682

What's wrong with my self-defined init method?

In ClassA:

- (ClassA *)initWithID:(NSString *) cID andTitle:(NSString *) cTitle {
    ClassAID = cID;
    ClassATitle = cTitle;
    return self;
}

In ClassB:

- (void)cellDidSelected {
    ClassA *classAController = [[ClassA alloc] init];
//Program received signal:  “EXC_BAD_ACCESS” when executing the following line.
    classAController = [classAController initWithClassAID:ClassAID andClassATitle:ClassATitle];
    NSLog(@"I want to get the value of ID:%@ and Title:%@ here.", [classAController ClassATitle], [classAController ClassAID])
}

Could anyone point where is wrong? Thanks a lot.

Upvotes: 0

Views: 144

Answers (2)

Tom Irving
Tom Irving

Reputation: 10069

Try using:

- (id)initWithID:(NSString*) cID andTitle:(NSString*) cTitle {

    if (!(self = [super init]))
       return nil;

    ClassAID = cID;
    ClassATitle = cTitle;
    return self;
}

Then you can just do something like:

ClassA * classA = [[ClassA alloc] initWithID:anID andTitle:aTitle];

And I would recommend having ClassAID and ClassATitle as properties if they're not already, and if they are you should be using:

[self setClassAID:cID];
[self setClassATitle:cTitle];

That way they'll be retained properly.

Upvotes: 1

fbrereto
fbrereto

Reputation: 35925

Typically the structure one would design for the situation you've posted above would include the call to [super init] within initWithID itself, so you would only have one init routine called per object instantiation. However I don't see that being the root cause of the problem you're seeing.

Upvotes: 0

Related Questions