2009-09-20 21 views
1

當它從一個UITableView委託方法中訪問實例變量時,我的iPhone應用程序爆炸。我想我會保留它,所以我不明白爲什麼我不能在沒有問題的情況下訪問它。從UITableView委託方法中訪問實例變量時獲取「EXC_BAD_ACCESS」

這是我的.h文件

#import <Foundation/Foundation.h> 
#import "AlertSummaryCell.h" 
#import "AlertDetailViewController.h" 

@interface AlertSummaryTableViewController : UITableViewController { 
NSDictionary *alerts; 
NSString *alertKind; 
} 

@屬性(非原子,保留)的NSDictionary *警報; @property(nonatomic,retain)NSString * alertKind;

@end

在我的.m,應用死在第一NSLog的呼叫:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
NSLog(@"AlertSummaryTableViewController.numberOfRowsInSection entered"); 
NSLog(@" alerts description = %@", [alerts description]); 
// To know how many alert summaries we have, get the value for count out of the input dictionary 
int theCount = [[alerts objectForKey:@"count"] intValue]; 
NSLog(@" Going to return %d",theCount); 
return theCount; 
} 

我在想什麼???

有沒有問題,在viewDidLoad方法都:

- (void)viewDidLoad { 
NSLog(@"AlertSummaryTableViewController.viewDidLoad entered"); 
NSLog(@" alerts description = %@", [alerts description]); 

// We want the View title to include the alert count 
// To know how many alert summaries we have, get the value for count out of the input dictionary 
int theCount = [[alerts objectForKey:@"count"] intValue]; 

// Now construct the title text and set our views title to it 
NSString *myTitle = [[NSString alloc] initWithFormat:@"%@ Alerts (%d)",alertKind,theCount]; 
[self setTitle: myTitle]; 

// Memory cleanup 
[myTitle release]; 

[super viewDidLoad]; 
} 

回答

4

對於任何EXC_BAD_ACCESS錯誤,你通常試圖將消息發送到一個釋放的對象。 BEST跟蹤這些的方法是使用NSZombieEnabled

這個作品永遠不會實際釋放一個物體,而是通過將其包裹爲一個「殭屍」並在其中設置一個標誌,表明它通常會被釋放。這樣,如果您嘗試再次訪問它,它仍然知道您發生錯誤之前是什麼樣的,並且通過這些信息,您通常可以回溯以查看問題所在。

當調試器有時在任何有用的信息上發現它時,它特別有助於後臺線程。

然而,非常重要的是要注意是,您需要100%確保這只是在您的調試代碼中,而不是您的分發代碼。因爲沒有任何東西會被釋放,你的應用程序將會泄漏並泄漏。提醒我要做到這一點,我把這篇日誌在我的appdelegate:

if(getenv("NSZombieEnabled") || getenv("NSAutoreleaseFreedObjectCheckEnabled")) 
    NSLog(@"NSZombieEnabled/NSAutoreleaseFreedObjectCheckEnabled enabled!"); 
+0

謝謝你的提示!!!!! – Dale 2009-09-20 13:42:25

0

我想你已經檢查,以提醒設置。如果你嘗試在nil引用上調用[alerts objectForKey:],你會得到那個錯誤。

0

問題原來是我設置警報的方式。而不是使用setter方法,這將保留該對象,我只是無知地這樣做:

alerts = [[UIDictionary alloc] init];  // or something like this 

其中沒有任何警告或錯誤,因爲它,我應該想編譯。

通過使用設定器,

[self setAlerts:[[UIDictionary alloc] init]; // again I'm going from memory so ... 

其中我必須創建,警報被「保留」,因爲它需要的是和所有很好一旦視圖控制器加載。

我對Objective-C非常陌生,不得不與內存管理混淆,但我終於在使用它和iPhone SDK約4周後開始看到光。