将节标题添加到uitableview后删除行的问题

时间:2013-10-17 13:19:46

标签: ios objective-c uitableview ios7

在将部分标题添加到我的应用程序中的某个表之前,我能够使用commitEditingStyle函数删除行而没有任何问题。我决定实现节标题,以便用户更容易查看按日期添加到表中的项目。此功能正常。我在实现节标题后删除行时遇到了问题,但感谢stackoverflow上的好人提供的帮助,问题得到了部分解决。经过一些测试后,我意识到如果行在同一部分,并且我尝试从该部分的顶行开始按顺序删除多行,则顶行删除正常但尝试删除第二行导致应用程序崩溃。如果我删除第一行以外的所有行,然后删除最后一行,它可以正常工作。 Xcode没有说明它在调试日志中崩溃的原因。

以下是cellForRowAtIndexPath函数的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    AgendaCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[AgendaCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }
    NSString *strDate = [dateArray objectAtIndex:indexPath.section];
    NSMutableArray *dateSection = [tempDict objectForKey:strDate];

    NSManagedObject *object = [dateSection objectAtIndex:indexPath.row];
    cell.sessionNameLabel.text = [object valueForKey:@"sessionname"];
    cell.sessionNameLabel.textColor = [UIColor blueColor];
    cell.sessionDateLabel.text = [object valueForKey:@"sessiondate"];
    cell.sessionDateLabel.textColor = [UIColor brownColor];
    cell.sessionTimeLabel.text = [object valueForKey:@"sessiontime"];
    cell.sessionTimeLabel.textColor = [UIColor brownColor];

    return cell;

}

以下是我的表刷新功能的代码:

- (void) refreshTable
    {

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Sessnotes"   inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"agenda == 'Yes'"]];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]  initWithKey:@"sessiondate" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

     NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest   error:nil];

        [self.refreshControl endRefreshing];
        self.objects = results;

    if (results.count == 0) {
        NSString *message = @"You have not added any sessions to your planner.";
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Notification"
                                                       message:message
                                                      delegate:self
                                             cancelButtonTitle:@"Ok"
                                             otherButtonTitles:nil,nil];
        [alertView show];
    }
    else if (results.count > 0){
    tempDict = nil;
    tempDict = [[NSMutableDictionary alloc] init];

    NSString *strPrevDate= [[results objectAtIndex:0] valueForKey:@"sessiondate"];
    NSLog(@"strPrevDate value is: %@", strPrevDate);
    NSString *strCurrDate = nil;
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    //Add the Similar Date data in An Array then add this array to Dictionary
    //With date name as a Key. It helps to easily create section in table.
    for(int i=0; i< [results count]; i++)
    {
        strCurrDate = [[results objectAtIndex:i] valueForKey:@"sessiondate"];

        if ([strCurrDate isEqualToString:strPrevDate])
        {
            [tempArray addObject:[results objectAtIndex:i]];
        }
        else
        {
            [tempDict setValue:[tempArray copy] forKey:strPrevDate];

            strPrevDate = strCurrDate;
            [tempArray removeAllObjects];
            [tempArray addObject:[results objectAtIndex:i]];
        }
    }
    //Set the last date array in dictionary
    [tempDict setValue:[tempArray copy] forKey:strPrevDate];

    NSArray *tArray = [tempDict allKeys];
    //Sort the array in ascending order
    dateArray = [tArray    sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    }

        [self.tableView reloadData];

}

这是commitEditingStyle函数的代码:

- (void)tableView:(UITableView *)tableView commitEditingStyle:   (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete

        NSManagedObject *object = [self.objects objectAtIndex:indexPath.row];

        NSManagedObjectContext *context = [self managedObjectContext];

        [context deleteObject:[context objectWithID:[object objectID]]];

        NSError *error = nil;
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }

        NSMutableArray *array = [self.objects mutableCopy];
        [array removeObjectAtIndex:indexPath.row];
        self.objects = array;
        [tableView reloadData];
    }
}

1 个答案:

答案 0 :(得分:0)

前面有几件事。每次你想重新加载tableview时我都不会发出获取请求。你应该看一下NSFetchedResultsController。它会自动将数据绑定到您的tableview,并根据来自相同NSManagedObjectContexts的更新或来自其他上下文的更新消息为您刷新,并为您批量处理。

回答您原来的问题。我会先尝试从数组中删除该对象然后删除NSManagedObject然后你可以使用一些tableview技巧:

NSManagedObject *managedObject = self.array[indexPath.row];
[self.array removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationAutomatic];
[context deleteObject:managedObject];

我可能错了,但你可能没有完成错误。希望有所帮助。