2012-01-02 139 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