Obj-C, переменная экземпляра, используемая, в то время как 'self' не установлено в результат '[(super или self) init ...]' - PullRequest
4 голосов
/ 13 ноября 2011

Я знаю, что задал похожий вопрос на этот вопрос не так давно, но я все еще немного не уверен в этом. Подобные вещи происходят в нескольких местах.

Переменная экземпляра, используемая, когда 'self' не установлено на результат '[(super или self) init ...]'

A

- (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

Для блока А это правильно

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

А, Б & С

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

1 Ответ

15 голосов
/ 13 ноября 2011

Как правило, вы должны написать:

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

Это потому, что init может не возвращать исходное значение self в некоторых случаях.

...