【问题标题】:Dispatch a NSNotification based on a custom core data setter基于自定义核心数据设置器调度 NSNotification
【发布时间】:2013-02-25 18:23:15
【问题描述】:
我想根据文档目录中是否存在文件来更改UITableViewCell。我觉得这应该是基于通知的,并且应该在对象isAvailable 属性发生更改时发送通知。
我不想意外造成线程问题。由于我在主线程上操作我的核心数据对象,是否可以在我的 Concrete 类上设置自定义设置器以发布通知?
最好的方法是什么?我应该创建自己的通知,还是应该挂钩核心数据已经发布的内容?
【问题讨论】:
标签:
ios
objective-c
cocoa-touch
cocoa
core-data
【解决方案1】:
如果您使用NSFetchedResultsController,这非常简单。此类可以与UITableView 结合使用,以减少内存开销并缩短响应时间。
您可以在 NSFetchedResultsController Class Reference 和 NSFetchedResultsControllerDelegate Protocol Reference 找到文档。
此外,您还可以为NSFetchedResultsController 实现委托方法。实现 NSFetchedResultsController 委托方法,它允许您侦听数据(您注册的 NSManagedObjectContext)以及表中的添加、删除、移动或更新等操作。
关于这个主题的一个非常好的教程是core-data-tutorial-how-to-use-nsfetchedresultscontroller。在这里您可以找到设置UITableView、NSFetchedResultsController 及其委托的所有元素。
这么说,关于您的问题,当isAvailable 属性(特定NSManagedObject)发生更改时,您可以使用此技术更改UITableViewCell 的内容。特别是,您应该实现以下委托方法以响应特定更改(请参阅注释)。
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate: // <---- here you will change the content of the cell based on isAvailable property
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray
arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray
arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
希望对你有帮助。