2011-06-30 8 views
0

iPhone 3.1.3用のアプリを開発しています。私はすべての初期化時にセットアップに自分のフィールド(形状、場所、範囲)を必要とするので、プログラマが-(id)init;を使わせたくない- (id)initを使わないでください。メソッド

@interface Pattern : NSObject { 

    NSMutableArray* shapes; 
    NSMutableArray* locations; 
    CGSize bounds; 
} 
@property (nonatomic, retain, readonly) NSMutableArray* shapes; 
@property (nonatomic, retain, readonly) NSMutableArray* locations; 

- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize)screenSize; 
- (void) addObject:(Object2D*) newObject; 

@end 

は、私は以下のクラスを持っています。

私は、プログラマがこれを使わせたくない:

Pattern* myPattern = [[Pattern alloc] init]; 

私が実装する方法を知っている:

- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize) screenSize{ 
    if (self = [super init]) { 
     shapes = [NSMutableArray arrayWithCapacity:numShapes]; 
     locations = [NSMutableArray arrayWithCapacity:numShapes]; 
     bounds = screenSize; 
    } 
    return (self); 
} 

私はそれをどのように行うことができますか?

答えて

5

誰かが平野init

- (id)init { 
    [NSException raise:@"MBMethodNotSupportedException" format:@"\"- (id)init\" is not supported. Please use the designated initializer \"- (id)initWithNumShapes:screenSize:\""]; 
    return nil; 
} 
+0

すばらしい答えです!どうもありがとう! – VansFannel

0

常に同じスキーマです。スーパークラス(NSObject)でinitを呼び出すだけです。

- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize)screenSize { 
    if(self == [super init]) { 
      // Custom Init your properties 
      myNumShapes = numShapes; 
      myScreenSize = screenSize; 
    } 
    return self; 
} 
+0

いいえ、申し訳ありません。私はとてもうまく説明していません。私は ' - (id)initWithNumShapes:(int)numShapes screenSize:(CGSize)screenSize'を実装する方法を知っています。私はプログラマが ' - (id)init;を使わないようにしたいです。 – VansFannel

2

を使用している場合は、init関数をオーバーライドすることができ、あなたが持っている場合は、それから、デフォルト値を与える例外を上げる:

- (id)init { 
    return [self initWith....]; 
} 

あなたはドンが」 initを全く必要とせず、依然としてオーバーライドし、initを使わないという例外を投げます。

- (id)init { 
    NSAssert(NO, @"Please use other method ...."); 
    return nil; 
} 

initに電話をかけようとすると、これは常に例外となります。

私は前者の場合を使用することを推奨し、いくつかのデフォルト値を持っています。

+1

NSAssertでブロックされた 'init'メソッドは警告を避けるために' nil'を返すべきです。 また、リリース構成で 'NS_BLOCK_ASSERTION'プリプロセッサマクロを有効にすると、デバッグモードでのみプログラマに警告され、リリースビルドにはコンパイルされません。 – toto

+0

リターン部分を修正しました:)。アサーションに関しては、コーディング中にプログラマーがデバッグモードでのみビルドすると感じています。少なくとも彼はすべきだ。しかし、取られたポイント:)。 – Sailesh

関連する問題