4

我知道不久前我问过类似的问题,但我仍然有点不确定。同样的事情发生在好几个地方。

'self' 未设置为 '[(super or 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;
}

- (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,这是否正确

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

和 B&C

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

1 回答 1

15

一般来说,你应该写:

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

这是因为在某些情况下init可能不会返回原始值。self

于 2011-11-13T12:52:03.620 回答