取消引用空指针,但我没有使用指针

Nic*_*oft 7 iphone debugging xcode code-analysis objective-c

我在xCode中进行了"构建和分析",并在我的init-method中将普通int设置为0时获得"空指针的取消引用".我在下面的代码中注意到我收到消息的行.我正在为iPhone开发.

Bric.m

#import "Bric.h"

@implementation Bric

- (id)initWithImage:(UIImage *)img:(NSString*)clr{
    if (self = [super init]) {
        image = [[UIImageView alloc] initWithImage:img];
    }   

    stepX = 0; //It's for this line I get the message
    stepY = 0;
    oldX = 0;
    color = [[NSString alloc]initWithString:clr];
    visible = YES;
    copied = NO;
    return self;
}   
@end
Run Code Online (Sandbox Code Playgroud)

Bric.h

#import <Foundation/Foundation.h>

@interface Bric : NSObject {

    int stepX;
    int stepY;

}  

-(id)initWithImage:(UIImage *)img:(NSString *)clr;

@end
Run Code Online (Sandbox Code Playgroud)

这不是完整的代码,粘贴我认为有用的东西.

由于我没有使用指针,我发现这很奇怪.我怎么得到这个消息?

谢谢和问候,尼克拉斯

Jas*_*ien 20

ifinit方法中的第一个语句是检查是否[super init]返回nil.(从技术上讲,它应该被编写if ((self = [super init])),新的LLVM编译器会警告你).

静态分析器正在检查所有可能的代码路径,即使是[super init]返回nil 的情况.在这种情况下,您的if语句失败并且selfnil.如果self是,nil则其实例变量不可访问.

要解决此问题,您需要将初始化内容放在if语句初始化的语句中,然后return self放在if语句之外.

  • 双括号告诉编译器先评估`self = [super init]`然后再将结果计算为布尔值.使用新的LLVM编译器,在`if`语句中没有围绕赋值的双括号将生成警告,因为编译器"智能地"询问您是否要使用`==`而不是`=`(这是一个做`if(x == 5)`之类的常见错误. (2认同)