Difference between writing to file atomically and not

Writing atomically takes more steps - additionally auxiliary file is created. NSString Class Reference explains:

If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

Here is the example in the case of pLists:

[array writeToFile:path atomically:YES];

when "YES", then pList is updated just once even if you run the code several times in XCode,

[array writeToFile:path atomically:NO];

when "NO" it is updated as many as you run the same code (repeated update).


Atomic in general means the operation cannot be interrupted will complete or have no effect. When writing files, that is accomplished by writing to a temporary file then replacing the original with the temporary when the write completes.

A crash while writing an atomic file means the original is not modified and there is a garbage file that can be deleted. A crash while writing normally would mean an expected good file is corrupt.

Performance wise the cost is minimal. During the write you will have two copies of a file. The file replace is a very simple operation at the file system level.

Edit: thanks zneak