Search code examples
iosnskeyedarchivernskeyedunarchiver

Is it possible to crash when I unarchive a file while deleting it?


For example

NSString *path = @"XXX";
id obj = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

and somewhere else is going to delete this file by removeItemAtPath, whether it is safe to do that? as I know, if I write an object to the file with archiver and I modify that object meanwhile, it will cause crash, but I don't understand the essence of the that, so I wonder what will happen if I operate like this.


Solution

  • No, it won't crash. A file isn't actually deleted until no process has the file open. As long as the unarchiver has the file open for reading, you can attempt to delete all you want without issue. Once the unarchiver is done and closes the file, then the OS will actually delete the file.

    That's a bit of an oversimplification to what really goes on but it should good enough for your question.

    For a more detailed explanation, see How do the UNIX commands mv and rm work with open files? and other similar questions. iOS is a Unix-type OS so when you read that question and the accepted answer, all mention of Unix applies to iOS. In case you aren't fluent in Unix, rm is the command to delete a file in Unix.