2010-10-05 49 views
1

我的代碼非常簡單。一個帶有實例變量「dataArray」的TableViewController,表格在視圖出現時填充。實例變量在同一個控制器中是未知的

問題:當我點擊其中一個條目(didSelectRowAtIndexPath)時,我的應用程序崩潰。 調試這個例子後,我發現,「dataArray」目前沒有對象,但爲什麼?我如何顯示被點擊的行?

頭文件

#import <UIKit/UIKit.h> 

@interface DownloadTableViewController : UITableViewController { 
NSMutableArray *dataArray; 
} 

@property (nonatomic, retain) NSMutableArray *dataArray; 

@end 

.m文件:

#import "DownloadTableViewController.h" 

@implementation DownloadTableViewController 

@synthesize dataArray; 

- (void)viewWillAppear:(BOOL)animated{ 
dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [dataArray count]; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    cell.textLabel.text = [dataArray objectAtIndex:indexPath.row]; 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
NSLog(@"%@", [self.dataArray objectAtIndex:indexPath.row]); 
} 


- (void)dealloc { 
    [super dealloc]; 
} 

@end 

回答

5

這條線:

dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 

應該是這樣的:

dataArray = [[NSMutableArray alloc] initWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 

self.dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 

[self setDataArray:[NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]]; 

的原因,你的應用程序崩潰是因爲dataArray會被自動釋放,所以你永遠使用它之前被釋放。

+0

非常感謝! :) – adamseve 2010-10-05 21:12:02

相關問題