Jakub
Jakub

Reputation: 13860

Designated initializer and calling it

I have general question about designated initializer. I have a some class and from there i want to call a initializer, but before i started to fill my @properties with passing data i want to make data default. For example:

-(id)initWithDefault:(NSDictionary*)defaultTemplate
{
    self = [super init];

    _fontColor = [defaultTemplate objectForKey:@"color"];
    _fontSize = [[defaultTemplate objectForKey:@"size"] intValue];

    return self;
}

-(id)initWithTemplate:(NSDictionary*)template
{
    self = [self initWithDefault:myDefaultTemplate];

    //now i doing something with my template

    return self;

}

Is this is a way to prevent null @properties? It this a correct use of designated initializer? Of course you can assume that myDefaultTemplates is not null, and has not null object in keys.

Upvotes: 1

Views: 89

Answers (2)

Dipak Mishra
Dipak Mishra

Reputation: 187

Your implementation is perfectly fine, given the fact that _fontColor and _fontSize variables are your local variables of properties.

adig's suggestion is just an enhancement on what you already have implemented. This check takes care of the situation, when your object does not get allocated due to any reason.

Upvotes: 0

adig
adig

Reputation: 4057

This seems fine with me. I would use the safe way (presented below), but otherwise your code is fine.

-(id)initWithTemplate:(NSDictionary*)template 
{
    if(self = [self initWithDefault:myDefaultTemplate]) {

        //now i doing something with my template

    }

    return self;

}

Upvotes: 2

Related Questions