我在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
Bric.h
#import <Foundation/Foundation.h>
@interface Bric : NSObject {
int stepX;
int stepY;
}
-(id)initWithImage:(UIImage *)img:(NSString *)clr;
@end
这不是完整的代码,粘贴我认为有用的东西。
由于我没有使用指针,我发现这很奇怪。我怎么得到这个消息?
谢谢和问候, 尼古拉斯
答案 0 :(得分:20)
init方法中的第一个if
语句是检查[super init]
是否返回nil
。 (从技术上讲,它应该写成if ((self = [super init]))
,新的LLVM编译器会警告你。
静态分析器正在检查所有可能的代码路径,即使[super init]
返回nil的情况也是如此。在这种情况下,您的if
语句失败,self
为nil
。如果self
为nil
,则无法访问其实例变量。
要解决此问题,您需要将初始化内容放在带有图像初始化的if
语句中,然后将return self
置于if语句之外。
答案 1 :(得分:0)
您是否将其声明为财产?我不确定在这种情况下是否有必要,但你没有制作存取方法(虽然我认为你仍然直接设置实例变量......)
即,在你的头文件中,
@property int stepX;
并在您的.m文件中
@synthesize stepX;
这将允许您以self.stepX和self.stepY的形式访问变量。
有时分析器会犯错误...我注意到它没有非常有效地处理while
循环。无论如何,看看如果你添加这些代码并回复我会发生什么。
答案 2 :(得分:0)
你的init方法错了。
它应该是这样的:
- (id)initWithImage:(UIImage *)img:(NSString*)clr
{
if (self = [super init]) // NB, this line should give you a waring
{
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;
}
我假设您收到的消息来自静态分析器。由于stepX是一个实例变量,行
stepX = 0;
是
的简写self->stepX = 0;
其中->
具有正常的C含义。由于该行在测试范围之外,代码中self不是nil,因此静态分析器标记了一个问题。