NSFileCoordinator correct usage
Asked Answered
E

1

6

when writing a file using NSFileCoordinator i need to specify the correct NSFileCoordinatorWritingOptions. Although they are explained in detail, I am not sure when to use which one. The available options are:

  • NSFileCoordinatorWritingForDeleting
  • NSFileCoordinatorWritingForReplacing
  • NSFileCoordinatorWritingForMoving
  • NSFileCoordinatorWritingForMerging

For example, what option is the correct one if I want to create a file (a plist for example)? Wich one when I modify a file?

Can someone explain the NSFileCoordinatorWritingOptions for a better understanding?

Enki answered 3/8, 2012 at 9:29 Comment(0)
Z
8

I agree, documentation is not complete on that front, and hard to understand. And no sample code is available even for basic operations like these.

I try to think of these options in the perspective of other apps that have that specific file open, that helps getting the whole picture.

  • Pass no option (0) to simply update the file and notify others of your changes.

  • Let's say you are deleting a file that TextEdit currently displays, by providing the NSFileCoordinatorWritingForDeleting option, you're telling TextEdit to close the file as it does not exist anymore (or it could propose to save it to another place if it's in memory). It acts because of deletion.

  • If you're overwriting a file (as opposed to updating a file), you want about that same behavior for other apps. That's NSFileCoordinatorWritingForReplacing.

  • NSFileCoordinatorWritingForMoving says other apps to track the file to it's new location, so that it can be later updated.

  • NSFileCoordinatorWritingForMerging asks other processes to first commit their changes so that you can then merge your own changes with those.

To answer your question, you should use NSFileCoordinatorWritingForReplacing when creating a new file (even when no file exists, as it was to appear in the mean time from another app, you'd be replacing it with your own, unrelated contents). And NSFileCoordinatorWritingForMerging should be used when updating an existing file with new data, as it allows integrating the latest changes to that file immediately (instead of doing later with conflict resolution).

Zither answered 11/12, 2012 at 7:24 Comment(1)
Forgive me if I'm wrong but there seems to be a contradiction in your answer: "Pass no option (0) to simply update the file" and "NSFileCoordinatorWritingForMerging should be used when updating an existing file with new data" — both allude to updating a file.Grapnel

© 2022 - 2024 — McMap. All rights reserved.