将NSDictionary对象设置为子视图中的属性,要么在未释放时泄漏,要么在释放时给出EXC_BAD_ACCESS错误



我有以下问题:在某个视图控制器中,我有一个NSDictionary,它本身是NSArray对象中的一个entree。这个视图控制器有一个子视图,它显示这个字典中的一些键值对。因为我只需要一些键值对,所以我构造了一个新的字典对象,然后从中删除我不想包含的键值对。为了能够在子视图中访问这个字典,我认为可以通过属性设置字典,这似乎工作得很好。用一些代码来说明:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    // today is an instance of NSArray holding a number of NSDictionary objects
    NSDictionary *completeData = [self.today objectAtIndex:row];
    NSDictionary *data = [[NSDictionary alloc] initWithDictionary:completeData];
    [data removeObjectForKey:@"name"];
    SomeViewController *childController = [[SomeViewController alloc] init];
    childController.data = data;
    [self.navigationController pushViewController:childController animated:YES];
    [childController release];
    // This results in a EXC_BAD_ACCESS error when navigating back to the parent 
    // view and calling didSelectRowAtIndexPath a second time. When commenting this 
    // line out, the error dissapears, but now the object leaks
    [data release];
}

问题出现时,返回到父视图后,我试图通过调用

将NSArray对象(今天)替换为自身的更新版本
- (void)refreshDataNotification:(NSNotification *)notification {
    if (notification) {
        self.today = [NSArray arrayWithArray:[[[MyAppDelegate getAppDelegate] todaySchedule]  
            objectForKey:@"data"]];
        [self.tableView reloadData];
    }
} 

请注意,只要我不释放'数据'在didSelectRowAtIndexPath我没有得到错误,但随后对象泄漏。当我释放它时,当执行refreshDataNotification时,我收到一个EXC_BAD_ACCESS。

如果有人有任何线索,我可能做错了,那么请与我分享。

将环境变量NSZombieEnabled设置为YES,以获得更多关于过度释放对象的有用错误消息。(通过查看'Executables'下的详细信息来设置环境变量)

另外,看看你是如何定义属性的也会很有帮助。(例如,SomeViewControllerdata的@属性是什么?)

ps -我知道你没有粘贴实际的代码,但是data对于NSDictionary来说是一个糟糕的实例名。dict是更好的——但是一些更具描述性的东西会让你的代码更容易理解。

最新更新