2011-06-30 46 views
0

我正在爲iPhone 3.1.3開發一個應用程序。不要讓 - - (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 

我不想讓程序員使用-(id)init;,因爲我需要設置我的字段(形狀,位置,邊界)上的每個初始化。

我不想讓程序員使用這樣:

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

可以覆蓋初始化函數,並從中得到默認值,如果你有一個例外:

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

如果你不」根本就不想要init,仍然會覆蓋並拋出某種不使用init的異常。

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

這總是會給一個例外,如果有人試圖撥打init

我會建議使用前一種情況,但有一些默認值。

+1

NSAssert-blocked'init'方法仍然應該返回nil來避免警告。 另外,如果您在發佈配置中啓用了'NS_BLOCK_ASSERTION'預處理器宏,它只會以調試模式警告程序員,而不會編譯到發佈版本中。 – toto

+0

修復了返回部分:)。關於斷言,我覺得在編碼過程中,程序員只能以調試模式構建。至少他應該。但要指出:)。 – Sailesh