代码之家  ›  专栏  ›  技术社区  ›  Nicsoft

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

  •  7
  • Nicsoft  · 技术社区  · 16 年前

    我在xcode中进行了“构建和分析”,并在init方法中将普通int设置为0时得到了“空指针的解引用”。我在下面的代码中注意到了我得到消息的行。我正在为iPhone开发。

    金砖四国

    #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
    

    金砖四国

    #import <Foundation/Foundation.h>
    
    @interface Bric : NSObject {
    
        int stepX;
        int stepY;
    
    }  
    
    -(id)initWithImage:(UIImage *)img:(NSString *)clr;
    
    @end
    

    它不是完整的代码,粘贴了我认为有用的东西。

    因为我没有用指针,我觉得这很奇怪。我怎么会收到这个信息?

    谢谢和问候, 尼克拉斯

    3 回复  |  直到 16 年前
        1
  •  20
  •   Jasarien    16 年前

    第一 if init方法中的语句正在检查是否 [super init] 收益率 nil . (技术上应该写 if ((self = [super init])) ,新的llvm编译器将警告您)。

    静态分析器正在检查所有可能的代码路径,甚至在 [超临界] 返回零。在这种情况下,您的 如果 语句失败,并且 self . 如果 自己 那么它的实例变量是不可访问的。

    要解决此问题,需要将初始化放在 如果 带有图像初始化的语句,然后 return self 在if语句之外。

        2
  •  0
  •   Helen    16 年前

    你把它申报为财产了吗?我不确定在这种情况下是否有必要,但您没有创建访问器方法(尽管我认为您仍然直接设置实例变量…)

    也就是说,在头文件中,

    @property int stepX;
    

    在你的.m文件中,

    @synthesize stepX;
    

    这将允许您访问变量self.stepx和self.stepy。 有时分析仪会出错…我注意到它不适合 while 循环非常有效。不管怎样,看看如果你添加这些代码行并返回给我会发生什么。

        3
  •  0
  •   JeremyP    16 年前

    初始化方法错误。

    它应该是这样的:

    - (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的测试范围内,静态分析器正在标记一个问题。