我有一个核心数据模型,定义如下:
用户有许多事件。每个事件可以有很多图片。关系具有"级联"删除规则。
我正在尝试了解如何在实体消失时删除本地文件。核心数据实体在消失之前是否调用某种 dealloc 或"最终化"方法?
每个图片实体都有对存储在应用文档目录中的本地文件的引用。
当通过表视图的 commitEditStyle 删除用户时,我可以通过逐步浏览关系来删除图像并手动删除文件:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
{
// Delete the managed object for the given index path
NSManagedObjectContext *context = [[[RKObjectManager sharedManager] objectStore] managedObjectContext];
AppUser* managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
//clean up local files before deleting the object
[self deleteLocalContentForAppUser:managedObject];
//now delete the object
[context deleteObject:managedObject];
// Save the context to remember deletion
NSError* error = nil;
if (![context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
但是,当通过其他方法删除实体,并且我的提取结果控制器收到有关它们的通知时,嵌套关系不包含任何对象。用户的事件集将没有任何实体要单步执行和删除本地内容。这是为关系设置的"级联"删除规则的结果吗?
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
// UITableView *tableView = self.tableView;
//
AppUser* managedObject = anObject;
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationNone];
// [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
// [self configureCell:[tableView cellForRowAtIndexPath:newIndexPath] atIndexPath:newIndexPath];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
//these methods cannot find any content to delete
[managedObject deleteLocalImages];
[managedObject deleteLocalContent];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[self.tableView cellForRowAtIndexPath:newIndexPath] atIndexPath:newIndexPath];
[managedObject updateLocalImages];
break;
case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
您可以在NSManagedObject
子类中实现prepareForDeletion
方法。在删除对象之前自动调用它,以便您也可以从那里删除引用的文件。