Search code examples
iosnsdatamemory-mapped-files

Deleting a memory-mapped files in iOS - what's going on behind the scenes?


I have a file which I memory-map with NSData. I then delete this file via an NSFileManager without any error, and proceed to check that the file is indeed not there (as far as NSFileManager and ls are concerned). However, I can still read data from the bytes pointer I got from NSData previously!

In the simulator, I sometimes get seemingly unrelated crashes. On the device, everything seems to work fine. I'm very curious to know what's going on, and what should I expect (what I expected in the past is to either get an error when trying to delete the file or a crash when I try to access it after it was deleted).

Thanks!


Solution

  • If you didn't unmap the memory, then the mmap you made with the file pointer is keeping the file from getting deleted (even though you cannot see it). you should always unmap memory before deleting the referenced file.

    [This relates to an old UNIX trick - open a file, once you have a file descriptor then unlink the file - you have a file you can do things with but no one can see, and if you crash the file completely goes away!]