我的代码非常简单。一个带有实例变量"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
发布于 2010-10-05 21:07:59
这一行:
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
是自动释放的,所以在你使用它之前就被释放了。
https://stackoverflow.com/questions/3867701
复制