How to handle cleanup of external data when deleting *unsaved* Core Data objects?

后端 未结 2 1132
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 05:23

In a managed object i have stored a path to an image file in the application\'s container.
When the managed object get’s deleted, the image file should be moved to trash

2条回答
  •  伪装坚强ぢ
    2021-01-05 05:47

    Excellent point - I updated my answer over on that question too, and I'll expand on my favorite approach here:

    1. Forget about will/did save. Not reliable in this case.

    2. Implement prepareForDeletion:. If you don't need undo, and are sure the deletion will succeed, delete the file on the spot. Otherwise, add the file to a convenient registry (a NSMutableSet owned by the context owner, or some such.)

    3. If you do need undo/redo, implement awakeFromSnapshotEvents: to catch un-deletion and re-deletion. Remove/re-add the file from/to the registry as needed.

    4. Register for a didSave notification somewhere convenient. When a save happens, delete all the files listed in the registry and clear it.

    This all assumes, by the way, that no two of your owning objects will ever own the same file. If this is a possibility, things get much more complicated - but I imagine you've set up your model specifically to avoid that happening.

提交回复
热议问题