【问题标题】:Delete an object from Core Data Model and update Table从核心数据模型中删除一个对象并更新表
【发布时间】:2014-07-24 14:14:56
【问题描述】:

我有一个 TableViewController (favTable.m),在 NSFetchedResultsController 的帮助下,它填充了从核心数据模型中提取的数据(1 个实体具有 2 个属性)。我在导航栏中包含了一个删除按钮,单击该按钮时应该删除表格的选定行以及核心数据模型中的相应对象。我将下面的代码用于删除按钮,但它返回错误[favTable delItem]: unrecognized selector sent to instance。我应该解决什么问题?

UIBarButtonItem *delButton = [[UIBarButtonItem alloc] initWithTitle:@"Del"
                                                              style:UIBarButtonItemStyleBordered
                                                             target:self
                                                             action:@selector(delItem)];

- (void)delItem:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.managedObjectContext = ((ecoAppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;

    FavoritesInfo*favoritesInfo = [self.fetchedResultsController objectAtIndexPath:indexPath];

    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [self.managedObjectContext deleteObject:favoritesInfo];

    NSError *error= nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }

    [self.tableView reloadData];

}

【问题讨论】:

  • 你是怎么调用这个方法的?如果这是按钮的直接操作,则它需要是 IBaction 而不是 void 方法。
  • 它是一个以编程方式设计的 UIBarButton。 @JayVersluis
  • 你方法的签名是:delItem:cellForRowAtIndexPath:,而不仅仅是delItem

标签: uitableview uibarbuttonitem delete-row nsfetchedresultscontroller


【解决方案1】:

您收到异常是因为您的方法的签名是:delItem:cellForRowAtIndexPath:,而不仅仅是delItem

在您的情况下,我认为您既不需要 tableView 也不需要 indexPath 作为参数。

相反,将您的 tableView 声明为一个属性(IBOutlet 以及如果从情节提要完成)。

@property (nonatomic) IBOutlet UITableView *tableView;

然后您可以使用self.tableView 访问它。

对于选中的行,可以使用indexPathForSelectedRow

NSIndexPath *selectedIndexPath = self.tableView.indexPathForSelectedRow;

现在您可以将 UIButton 的操作重写为:

- (void) deleteSelectedItem {
    NSIndexPath *selectedIndexPath = self.tableView.indexPathForSelectedRow;
    //Delete the item using your code
}

【讨论】:

  • 谢谢您的回答。我尝试了您的建议,但出现此错误:-[UITableView _endCellAnimationsWithContext:] 中的断言失败,/SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:1037 '无效更新:第 0 节中的行数无效。行数更新后包含在现有节中的行数 (3) 必须等于更新前该节中包含的行数 (3),加上或减去从该节插入或删除的行数(0 插入,1 删除)加上或减去移入或移出该部分的行数(0移入,0移出)。'
  • 好吧,这个错误很可能与您的答案无关。你解决了我的问题。谢谢
  • 您会收到该错误,因为当您添加/删除单元格时,数据源不会反映它。如果您无法解决,请发布其他问题。
猜你喜欢
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
相关资源
最近更新 更多