2011-05-16 49 views
1

我遇到了一個我無法解釋的錯誤。現在我發現了這個bug,我當然可以修復它,但我想知道這種事情甚至會發生。無法解釋如何在可可中修改指針值

我的代碼:

NSLog(@"1 - self.nextPlayerButton = %@",self.nextPlayerButton); 
    NSLog(@"[self.view setUserInteractionEnabled:TRUE] with self.view=%@",self.view); 
    [self.view setUserInteractionEnabled:TRUE]; 
    NSLog(@"2 - self.nextPlayerButton = %@",self.nextPlayerButton); 

其中nextPlayerButton被定義爲:

@property (retain) IBOutlet UIBarButtonItem *nextPlayerButton; 

日誌:

2011-05-15 15:23:05.245 Melimemo[1261:207] 1 - self.nextPlayerButton = <UIBarButtonItem: 0x4b668c0> 
2011-05-15 15:23:05.248 Melimemo[1261:207] [self.view setUserInteractionEnabled:TRUE] with self.view=<UIView: 0x4b69750; frame = (0 0; 320 460); autoresize = W+H; layer = <CALayer: 0x4b54290>> 
2011-05-15 15:23:05.249 Melimemo[1261:207] 2 - self.nextPlayerButton = <UIBarButtonItem: 0x4b65880> 

正如你所看到的,self.nextPlayerButton點到另一個對象第二次。

我的問題的根源是,self.view實際上沒有正確定義:我初始化一個對象的實例,其中下面的代碼運行並且不定義什麼視圖。不過,如何調用上的setUserInteractionEnabled任何東西導致修改self.nextPlayerButton的指針值?即使是理論的開始也會有所幫助。

回答

0

更可能的是self.view調用導致loadView被調用,並且您的按鈕被第二次設置爲新按鈕。

嘗試實施了nextPlayerButton二傳手是這樣的:

- (void)setNextPlayerButton:(UIButton *)button { 
    if (button != nextPlayerButton) { 
     [nextPlayerButton release]; 
     nextPlayerButton = [button retain]; 
    } 
} 

然後把一個破發點在那裏並運行你的應用程序。中斷點可能會被擊中兩次。您可以查看堆棧跟蹤,瞭解它爲何會遇到意外時間。

+0

對。確實被稱爲兩次。現在讓我困惑的是爲什麼。跟蹤顯示loadView被調用,因爲視圖被調用,並且我調用視圖,如上面的代碼所示。很顯然,每次調用視圖時都不會調用loadView,那麼它是什麼時候? – double07 2011-05-18 03:23:53

+0

我相信loadView是調用視圖調用時,如果視圖目前爲零。你有沒有偶然setView:零在某個時間點?這是iOS還是Mac OS X? – 2011-05-18 03:41:20

+0

iOS。爲什麼這是相關的?不,沒有將視圖設置爲零,至少明確地說,在setView中編寫和設置一個BP沒有透露任何東西。至少,通過編寫方法並插入一個BP,我現在可以更好地瞭解如何在未來發現這類錯誤。謝謝您的幫助! – double07 2011-05-21 14:27:29