2012-01-02 130 views
2

我在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; 

} 

这不是完整的代码,粘贴什么,我认为是非常有用的。

我觉得这很奇怪。我怎么得到这个消息?

enter image description here

回答

8

如果自我是零,那么你就可以'访问'self'的实例变量。所以你应该只在if语句中引用这些变量。换句话说,只有自我不是零。

- (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; 
} 
+0

谢谢您的回答。它的第一次尝试工作 – 2012-01-02 07:24:50

1

appDelegate类的一个实例变种?如果是这样,你应该在if (self =....。与[self addSubview...]相同。基本上如果这个if语句失败了,你就没有一个对象可以使用。

0

appDelegate实际上是[self appDelegate],所以如果您将空值分配给self,那么您将取消引用空指针。

无论如何 - self指向当前对象,为什么要指定它?您可以直接使用它,而无需分配任务。

而最后一件事 - 你使用self明确在对前方的最后一行,无论如何,这里很明显,这是空:

[self addSubview:pdfView]; 
+0

谢谢您的回答 – 2012-01-02 07:25:23