在尝试基于uinavigationcontroller的iPhone应用程序时,当用户导航回前一个视图时,我遇到了一个问题。
简单应用程序使用uinavigationController,将uiviewController的新实例推送到它上面。
这些实例都属于同一类(在本例中,类myviewcontroller是uiviewcontroller的子类),并且是手动创建的(不使用NIB)。每个实例都包含一个单独的uiViewView实例作为uiViewController的视图。
以下tableview:didselectrowatindexpath:方法来自MyViewController类。当用户选择表单元格时,它将创建另一个MyViewController实例并将其推送到NavigationController上:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MyViewController *nextViewController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:nextViewController animated:YES];
[nextViewController release];
}
用户可以在一系列视图中向前导航,每个视图包含一个表。回到上一个屏幕时出现问题。应用程序中止,Xcode启动调试器。
如果不在上面的tableview:didselectrowatindexpath:method中释放myviewcontroller实例,或者不在myviewcontroller的dealloc方法中的“mytableview”实例上调用dealloc,则可以防止此错误。
然而,这不是真正的解决方案。据我所知,uinavigationController“拥有”推送的uiviewController实例,然后可以从分配该实例的客户机安全地释放该实例。那么,这个实验应用程序有什么问题呢?为什么当用户导航回来时它会终止?
下面是MyViewController类的一些其他方法:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
self.title = @"My Table";
myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
myTableView.delegate = self;
myTableView.dataSource = self;
self.view = myTableView;
}
return self;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyTable"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0,0, 300, 50) reuseIdentifier:@"MyTable"];
[cell autorelease];
}
cell.text = [NSString stringWithFormat:@"Sample: %d", indexPath.row];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3; // always show three sample cells in table
}
- (void)dealloc {
[myTableView dealloc];
[super dealloc];
}
编辑:
问题已解决-感谢Rob Napier指出问题所在。
-loadView方法现在使用本地UITableView实例设置视图:
- (void)loadView {
UITableView *myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
myTableView.delegate = self;
myTableView.dataSource = self;
self.view = myTableView;
[myTableView release];
}