【问题标题】:Dereference of null pointer,warning取消引用空指针,警告
【发布时间】:2012-01-02 15:24:53
【问题描述】:

我在 xCode 中进行了“构建和分析”并获得了“空指针的取消引用”。我在下面的代码中指出了我收到消息的行。我正在为 iPhone 开发。

“PDFScrollView.h”

 #import "ENsightAppDelegate.h"
@interface PDFScrollView : UIScrollView <UIScrollViewDelegate> {

ENsightAppDelegate *appDelegate;
}

 @end

“PDFScrollView.m”

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

    // Set up the UIScrollView
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.bouncesZoom = YES;
    //self.decelerationRate = UIScrollViewDecelerationRateFast;
    self.delegate = self;
    [self setBackgroundColor:[UIColor grayColor]];
    self.maximumZoomScale = 5;//200
    self.minimumZoomScale = 0.5;//.85
    self.userInteractionEnabled = YES;
    self.delaysContentTouches = YES;
    self.canCancelContentTouches = NO;

}
appDelegate =(ENsightAppDelegate *) [[UIApplication sharedApplication] delegate];
pdfView=[appDelegate GetLeaveView];
[self addSubview:pdfView];
return self;

}

不是完整的代码,贴上我觉得有用的。

我觉得这很奇怪。我怎么会收到这条消息?

【问题讨论】:

    标签: iphone objective-c debugging code-analysis


    【解决方案1】:

    如果 self 是 nil,那么你不能访问 'self' 的实例变量。因此,您应该仅在 if 语句中引用这些变量。换句话说,只有当 self 不为零时。

    - (id)initWithFrame:(CGRect)frame {
    
       if ((self = [super initWithFrame:frame])) {
    
          // Set up the UIScrollView
          self.showsVerticalScrollIndicator = NO;
          // ... bunch of other properties set...
          // ... btw, better style here would be to set the ivars directly (in an initializer)
    
          appDelegate =(ENsightAppDelegate *) [[UIApplication sharedApplication] delegate];
          pdfView=[appDelegate GetLeaveView];
          [self addSubview:pdfView];
        }
    
        return self;
    }
    

    【讨论】:

      【解决方案2】:

      appDelegate 是类的实例变量吗?如果是这样,您应该在if (self =.... 中进行操作。与[self addSubview...] 相同。基本上,如果该 if 语句失败,则您没有可使用的对象。

      【讨论】:

        【解决方案3】:

        appDelegate实际上是[self appDelegate],所以如果你给self赋值null,你就取消了对空指针的引用。

        无论如何 - self 指向当前对象,为什么要分配给它?无需赋值即可直接使用。

        最后一件事 - 你在最后一行之前明确使用self,这里很明显它是空的:

        [self addSubview:pdfView];
        

        【讨论】:

          猜你喜欢
          • 2021-03-21
          • 2014-06-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-27
          • 2015-01-13
          • 1970-01-01
          • 2013-02-20
          相关资源
          最近更新 更多