需要有关UIViewController生命周期的帮助

时间:2013-05-02 07:42:15

标签: ios objective-c memory-management

在基于聊天的应用中,我UITableView显示所有朋友的姓名,didSelectRowAtIndex我正在使用chatViewController navigationcontroller方法推送到push。< / p>

我有两个困惑:

1&GT;当我按chatViewController时,我会这样做

 chatViewController *cVc = [[chatViewController alloc]initWithFriendName:@"the name" andId:@"the id"];

可以有10个或50个或100个朋友,为每个朋友拨打alloc init是否正确?

2 - ;当用户点击后退按钮返回朋友列表时,当chatViewController's当前实例被销毁以释放内存时会发生什么?

2 个答案:

答案 0 :(得分:2)

  1. 是的,如果chatViewController的此实例适用于此特定朋友。

  2. 后退按钮执行弹出的隐式popViewControllerAnimated: 来自导航堆栈的chatViewController并将其销毁(除非你有 在某处保存了对该视图控制器的强引用。

  3. 因此,一次只有chatViewController的一个实例(在 didSelectRowAtIndex popViewControllerAnimated:被{{1}}摧毁 用户返回表格视图)。

答案 1 :(得分:0)

由于您正在创建chatViewController的全局实例并在每次调用didSelectRowAtIndexpath:方法时分配它,这是错误的方式,因为它不一定会利用内存,从而降低应用程序性能。您必须在方法didSelectRowAtIndexpath:

中创建本地实例
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     ChatViewController *_cvc = [[ChatViewController alloc] initWithFriendName:@"the name" andId:@"the id"];

     [self.navigationController pushViewController:_cvc animated:YES];
}

第二个问题的答案是,只要用户按下后退按钮,实例就会被销毁