指定初始化程序并调用它

时间:2012-05-08 09:58:53

标签: objective-c ios

我对指定的初始化程序有一般性的疑问。我有一个类,从那里我想调用一个初始化程序,但在我开始用传递数据填充我的@properties之前我想让数据默认。例如:

-(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;

}

这是一种防止null @properties的方法吗?这是正确使用指定的初始化程序吗?当然,您可以假设myDefaultTemplates不为null,并且键中没有null对象。

2 个答案:

答案 0 :(得分:2)

这对我来说似乎很好。我会使用安全的方式(如下所示),否则你的代码就可以了。

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

        //now i doing something with my template

    }

    return self;

}

答案 1 :(得分:0)

由于_fontColor和_fontSize变量是属性的局部变量,因此您的实现完全没问题。

adig的建议只是对您已经实施的内容进行了改进。当您的对象因任何原因未被分配时,此检查会处理这种情况。

相关问题