通过UITableView从NSMutableArray中删除项目

时间:2012-11-10 15:01:28

标签: iphone objective-c uitableview nsmutablearray plist

您好

我想通过UITableView从NSMutableArray中删除项目,但有些东西会使应用程序崩溃。 崩溃是“0 objc_msgSend”。

这是我的代码人员:

- (void)viewDidLoad
{
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    path = [basePath stringByAppendingPathComponent:@"favoris.plist"];
    dict = [[NSArray arrayWithContentsOfFile:path] mutableCopy];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    [dict removeObjectAtIndex:indexPath.row];

    [self.tableView reloadData];
}

由于

1 个答案:

答案 0 :(得分:0)

EXEC_BAD_ACCESS绝对意味着有一个僵尸,所以我认为你的内存管理有些奇怪,而且可能是因为你实例化数组。在Instruments中运行Zombies工具绝对会为您提供更多信息,但这里有一些尝试:

(另一个建议是,为什么要将NSArray的变量命名为dict?)。

试试这段代码:

- (void)viewDidLoad
{
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    path = [[basePath stringByAppendingPathComponent:@"favoris.plist"] retain];
    dict = [[NSMutableArray alloc] initWithContentsOfFile:path];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [dict removeObjectAtIndex:indexPath.row];
    [dict writeToFile:path atomically:YES]; 
    [self.tableView reloadData];
}

这个建议的基础是,我怀疑在自动释放的对象上调用copy会产生意想不到的后果。