2012-05-04 4 views
1

私はそのように定義された指定イニシャライザを持つクラスを作成しました:指定イニシャライザとinitWithFrame

-(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]); 
} 

これは良い解決策ですか?

答えて

4

aPropertyのデフォルト値で指定された初期化子を呼び出すのはどうですか?

+0

これは、単純な良い解決策:) – MatterGoal

+0

うんあり、そしてそれはちょうど 'initWithFrame呼び出すコードを中断されません:' 'aProperty'のための適切なデフォルト値は何を知っていないこともできます。そして 'aProperty'を後で変更できるようにすると、目立たないことさえあります。 – Cyrille

1

私はイニシャライザで使用する2つの手法です。私はそこにもっと確信している。

テクニック1:initWithFrameで

プロパティ

- (id)initWithFrame:(CGRect)frame 
{ 
    return [self initWithFrame:frame aProperty:1.0f]; 
} 

技術2のデフォルト値を使用してイニシャライザを呼び出します。

単にnilを返します。

- (id)initWithFrame:(CGRect)frame 
{ 
    return nil; 
} 
関連する問題