2011-11-13 3 views
4

私はこれまでにこれに似た質問をしましたが、まだそれについて少し不明です。同じ種類のことがいくつかの場所で起こります。 '自己' が '[(superまたは自己)INIT ...]'Obj-C、 'self'が '[(スーパーまたは自己)init ...]の結果に設定されていないときに使用されるインスタンス変数

- (id)initWithCoder:(NSCoder *)decoder { 
    if (![super init]) return nil; 
    red = [decoder decodeFloatForKey:kRedKey]; //occurs here 
    green = [decoder decodeFloatForKey:kGreenKey]; 
    blue = [decoder decodeFloatForKey:kBlueKey]; 
    return self; 
} 

Bの結果に設定されていない状態

インスタンス変数が使用

- (id)initWithFrame:(CGRect)frame title:(NSString*)str sideUp:(BOOL)up{ 

    if(![super initWithFrame:frame]) return nil; 

    int y; 
    UIImage *img; 

    if(up){ 
     img = [UIImage imageNamedTK:@"TapkuLibrary.bundle/Images/graph/popup"]; 
     y = 5; 
    }else{ 
     img = [UIImage imageNamedTK:@"TapkuLibrary.bundle/Images/graph/popdown"]; 
     y = 14; 
    } 

    background = [[UIImageView alloc] initWithImage:img]; // occurs here 

C

- (id) initWithFrame:(CGRect)frame { 
    if(![super initWithFrame:frame]) return nil; 

    UILabel *titleBackground = [[[UILabel alloc] initWithFrame: 
      CGRectMake(0, 0, 480, 40)] autorelease]; 
    titleBackground.backgroundColor = [UIColor whiteColor]; 
    [self addSubview:titleBackground]; 

    titleLabel = [[UILabel alloc] initWithFrame:CGRectZero]; // occurs here 

ブロックAの場合、t

self = [self init]; 
if(self != nil) 
{ 

そしてB & C

- (id) initWithFrame:(CGRect)frame { 
    super = [super initWithFrame:frame] 
    if(super != nil) 
    { 
+2

これは質問ですか?もしそうなら***は何ですか***? –

+0

あなたがサブクラスを書くなら、super – SAKrisT

答えて

15

彼の正しいは一般的に、あなたが書くことになっている:

self = [super init...]; // Potentially change "self" 
if (self) { 
    something = x; 
    another = y; 
} 
return self; 

initは、いくつかのケースでは、元self値を返さない場合がありますので、これは、 。

+0

あなたの明確で技術的な答えに感謝します...なぜ 'self = [super'ではなく' self' [self'? – Jules

+3

あなたは 'init 'のバージョンが' [super init ...] '呼び出しを実行すると' self = [self init ...] 'を使うことができますいくつかのケースで行うべきである。 (実際には、 'init'がライブラリクラスのカテゴリに含まれていれば必須です)しかし、' super'バージョンが最終的に呼び出されるか、オブジェクトが不完全であることを確認する必要があります。 –

関連する問題