我有一个核心数据模型定义如下:
一个用户有很多事件。每个事件可以有许多图片。关系具有“级联”删除规则。
我正在尝试了解如何在实体消失时删除本地文件。核心数据实体在消失之前是否会调用某种 dealloc 或“finalize”方法?
每个图片实体都有一个对存储在应用文档目录中的本地文件的引用。
当通过table view的commitEditingStyle删除用户时,我可以通过关系逐步删除图像并手动删除文件:
- (void)tableViewUITableView *)tableView commitEditingStyleUITableViewCellEditingStyle)editingStyle forRowAtIndexPathNSIndexPath *)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();
}
}
}
但是,当通过其他方法删除实体时,当我的获取结果 Controller 收到通知时,嵌套关系不包含任何对象。用户的事件集将没有任何实体可以单步执行并删除本地内容。这是为关系设置“级联”删除规则的结果吗?
- (void)controllerNSFetchedResultsController *)controller didChangeObjectid)anObject
atIndexPathNSIndexPath *)indexPath forChangeTypeNSFetchedResultsChangeType)type
newIndexPathNSIndexPath *)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;
}
}
Best Answer-推荐答案 strong>
您可以在 NSManagedObject 子类中实现 prepareForDeletion 方法。它在删除对象之前自动调用,因此您也可以从那里删除引用的文件。
关于iPhone iOS如何在删除实体时删除从Core Data实体嵌套关系引用的本地文件?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/10419201/
|