简体   繁体   中英

Standard temporary directory in OSX

I'm trying to figure what is the best place where to store temporary files in the OSX version of my application.

The obvious answer /tmp is not good since it is cleaned up at boot and my application may need to continue an interrupted job also after a restart.

I tried also to use the path pointed by the environment variable TMPDIR , that is the same returned by NSTemporaryDirectory() , that changes every boot and is something like:

/var/folders/wx/p4rqqs8d1ws0wlpx9dkwsh_80000gn/T/

.. but also the contents of this path are removed at boot.

There is a standard path where I can place some temporary files, resilient to restarts, or I have to invent my own solution (ie ~/Library/myapplication/temp)?

In Windows I'm using GetTempPath() and it works the way it should.

I've found my answer googling harder that I did before asking here, in this excellent article:

https://www.cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.html

Reading the articles and the various options I found that the Caches directory (NSCachesDirectory) is the correct place where to store my files. Placing them in "Application Support" will cause them to be backed up by time machine.

So here is what I did:

const char *get_temporary_dir()
{
    NSString *path = nil;
    NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    if ([paths count]) {
        path = [[paths objectAtIndex:0] stringByAppendingPathComponent:bundleName];
    } else {
        path = NSTemporaryDirectory();
        path = [path stringByAppendingPathComponent:bundleName];
    }
    return [path UTF8String];
}

... I'm not sure if the fallback to the standard, deletable, directory is needed but it doesn't hurt!

You should use the "application support directory" - this is typically ~/Library/Application Support or for a sandboxed application and equivalent within its container.

To obtain the URL for this directory you use URLForDirectory:inDomain:appropriateForURL:create:error: passing as first argument NSApplicationSupportDirectory .

Within this directory you need to create a directory just for your application, using your app's bundle ID is a common strategy for naming this directory.

This directory is intended to store files needed by your application, but not your user's files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM