Obj-C, Instance variable used while 'self' is not set to the result of '[(super or self) init…]'

冷暖自知 提交于 2019-11-30 17:45:56

问题


I know I asked a similar question to this not long ago, but I'm still a little unsure about it. The same sort of thing happens in several places.

Instance variable used while 'self' is not set to the result of '[(super or 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

For block A, is this correct

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

And B & C

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

回答1:


Generally, you're supposed to write:

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

This is because init may not return the original self value in some cases.



来源:https://stackoverflow.com/questions/8111549/obj-c-instance-variable-used-while-self-is-not-set-to-the-result-of-super

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!