我创建了一个具有指定初始化程序的类:
-(id)initWithFrame:(CGRect)frame
aProperty:(float)value {
self = [super initWithFrame:frame];
if(self){
///....do something
}
}
现在我想知道如何避免直接调用initWithFrame方法,例如:
MyClass *theObj = [MyClass alloc]initWithFrame:theFrame];
我考虑过在initWithFrame定义中抛出异常:
- (id)initWithFrame:(CGRect)frame
{
@throw ([NSException exceptionWithName:@"InitError"
reason:@"This class needs to be initialized with initWithFrame:aProperty: method"
userInfo:nil]);
}
这是一个很好的解决方案吗?
答案 0 :(得分:4)
如果使用aProperty
的默认值调用指定的初始化程序呢?
答案 1 :(得分:1)
我使用初始化器的两种技术。我相信还有更多。
技术1:
在initWithFrame中使用Property
的默认值调用初始值设定项- (id)initWithFrame:(CGRect)frame
{
return [self initWithFrame:frame aProperty:1.0f];
}
技术2:
简单地返回nil;
- (id)initWithFrame:(CGRect)frame
{
return nil;
}