简体   繁体   中英

Delete items from NSMutableArray through UITableView

Hi

I want to delete items from a NSMutableArray through a UITableView but something crash the app. The crash is " 0 objc_msgSend ".

Here's my code guys:

- (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];
}

Thanks

EXEC_BAD_ACCESS absolutely means there's a zombie, so I think there's some weirdness going on with your memory management, and it's probably happening due to how your instantiating the array. Running the Zombies tool in Instruments will absolutely give you more information, but here's something to try:

(another suggestion, why are you naming a variable for an NSArray as dict?).

Try this code:

- (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];
}

The basis for this suggestion is that I'm suspecting that calling copy on an autoreleased object will have unexpected consequences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM