Objective c 指定初始值设定项和initWithFrame
我创建了一个类,指定的初始值设定项是这样定义的:Objective c 指定初始值设定项和initWithFrame,objective-c,ios,Objective C,Ios,我创建了一个类,指定的初始值设定项是这样定义的: -(id)initWithFrame:(CGRect)frame aProperty:(float)value { self = [super initWithFrame:frame]; if(self){ ///....do something } } 现在我想知道如何避免直接调用initWithFrame方法,如: MyClass *theObj = [MyClass
-(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]);
}
这是一个好的解决方案吗 用
aProperty
的默认值调用指定的初始值设定项怎么样?用aProperty
的默认值调用指定的初始值设定项怎么样?我对初始值设定项使用的两种技术。我肯定还有更多的
技术1:
在initWithFrame中,使用属性的默认值调用初始值设定项
- (id)initWithFrame:(CGRect)frame
{
return [self initWithFrame:frame aProperty:1.0f];
}
技术2:
简单地返回零
- (id)initWithFrame:(CGRect)frame
{
return nil;
}
我对初始值设定项使用两种技术。我肯定还有更多的 技术1: 在initWithFrame中,使用属性的默认值调用初始值设定项
- (id)initWithFrame:(CGRect)frame
{
return [self initWithFrame:frame aProperty:1.0f];
}
技术2:
简单地返回零
- (id)initWithFrame:(CGRect)frame
{
return nil;
}
是的,这不会破坏只调用
initWithFrame:
的代码,因为不知道aProperty
的默认值是多少。如果您允许在之后更改aProperty
,它甚至不会引起注意。是的,这不会破坏只调用initWithFrame:
的代码,因为不知道aProperty
的默认值是多少。如果您允许在之后更改属性,它甚至不会被注意到。