在尝试删除行时在TableViewController中获取NULL - 使用viewWillAppear删除该行

时间:2013-10-12 11:45:01

标签: ios tableview

我有一个简单的程序,它是一个调用ModalViewController的TableViewController,用户在文本字段中添加一些文本,单击保存并将其添加回TableViewController。

我正在尝试滑动以删除行,当我这样做时,值会更改为“NULL”并且行仍然存在。如果我重新启动应用程序或转到另一个View Controller并再次返回,则该行将消失。

我的代码如下所示:

@interface NewTimelineViewController () <UITableViewDataSource, UITableViewDelegate>
@property (strong) NSMutableArray *transactions;
@end

@implementation NewTimelineViewController

@synthesize transactions = _transactions;

- (NSManagedObjectContext *)managedObjectContext
{       
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication]delegate];
    if ([delegate performSelector:@selector(managedObjectContext)])
    {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.transactions.count;
}

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

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

    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self.managedObjectContext deleteObject:[self.transactions objectAtIndex:indexPath.row]];

        NSError *error = nil;
        if (![self.managedObjectContext save:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            //abort();
            //[self.tableView reloadData];       
        }
    }
}

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

    NSManagedObject *transaction = [self.transactions objectAtIndex:indexPath.row];

    [cell.textLabel setText:[NSString stringWithFormat:@"%@ %@", [transaction valueForKeyPath:@"whoBy.name"], [transaction valueForKeyPath:@"gifting.amount"]]];

    return cell;
}

我知道这很容易;对我而言,在这个视图中看起来实际的行没有被删除或重新加载,但是当这个TableView再次出现时,它就消失了。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

您还需要从数据源中删除对象(可能是数组)然后重新加载表视图(通过重新加载或更加不显眼的方式,如reloadRowsAtIndexPaths)

答案 1 :(得分:0)

你需要提供一个实现     - (void)tableView:(UITableView *)tableView commitEditingStyle(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath; UITableView的数据源方法。

在此方法中,您应该从transactions数组中删除该值,然后调用tableView的reloadData或deleteRowsAtIndexPaths作为用户已选择删除的行的索引路径。

答案 2 :(得分:0)

您刚刚从数据库中删除了该对象,

[self.managedObjectContext deleteObject:[self.transactions objectAtIndex:indexPath.row]];

但是您在成功后忘记将其从数据源self.transactions中删除,

[self.transactions removeObjectAtIndex:indexPath.row];

并记住重新加载表视图或删除已删除对象的表视图单元格。