【问题标题】:Obj-C, Instance variable used while 'self' is not set to the result of '[(super or self) init...]'Obj-C,“self”未设置为“[(super or self)init ...]”的结果时使用的实例变量
【发布时间】:2011-11-13 12:35:03
【问题描述】:

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

在 '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;
}

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区,这样对吗

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

和B&C

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

【问题讨论】:

  • 这是一个问题吗?如果是这样,的问题是什么?
  • 如果你写子类,使用super

标签: objective-c xcode cocoa-touch analyzer


【解决方案1】:

一般来说,你应该写:

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

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

【讨论】:

  • 感谢您明确且没有技术性的回答...为什么是self =[super 而不是self = [self
  • 如果您最终要调用的init... 版本执行[super init...] 调用,您可以使用self = [self init...],在某些情况下可能会这样做。 (事实上​​,如果您的 init 属于库类的一个类别,这几乎是强制性的。)但是您需要确保最终调用 super 版本,否则您的对象将不完整。
猜你喜欢
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多