Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 指定初始值设定项和initWithFrame_Objective C_Ios - Fatal编程技术网

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
的默认值是多少。如果您允许在之后更改
属性,它甚至不会被注意到。