Cautionary tale about [NSFilemanager URLForDirectory:inDomain:appropriateForURL:create:error:]

tl:dr; Using Apple’s functions to provide atomic saving, require manual cleanup after the fact, otherwise your application is unable to save any files.

In my quest to address the temporary folder issue that some of my customers had with Catalina, it was suggested to me to use the recommended function of [NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:]. While my solution to the problem was to use the “Caches” folder instead of the temporary folder, I used this function and it’s corresponding partner [NSfileManager replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:] with some of my save routines to provide OS supplied atomic saving.

All’s well, except that this week, while trying to debug another issue (which I’m 100% certain is a bug in Apple framework), my apps started getting an error when it was saving, specifically when using the first API to ask for a location to create the temporary file. Error 502 Create create file.

After being unable to find anything helpful to error 502, I decided to go spelunking in my system to see if I could spot anything in the temporary folder. Bearing in mind that when the function fails, it doesn’t give you a location as to where it was trying to access.

I finally found it, and to my surprise the temporary folder for my application contained 512 empty folders. I deleted those folders, and tried my app, it now works again, but I noticed that each time auto save kicks in, a new blank folder is created. It’s easily solved by removing the parent folder of the item after you’re done replacing, but as I couldn’t find it documented anywhere or any mention of this issue online, I thought I’d post it so it might help someone else.

I assume that once you restart the computer these files are automatically removed, it’s been two weeks since I last restarted and yes other things are going wonky, but I’m using this opportunity to try and improve my apps handling of these wonky things.