将文件从应用程序包复制到用户的Application Support文件夹

pme*_*ino 2 macos xcode cocoa nsfilemanager

我正在创建一个应用程序,我需要将某个文件从应用程序包复制到用户的Application Support文件夹.这是我实际使用的代码:

NSBundle *thisBundle = [NSBundle mainBundle];
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *userpath = [paths objectAtIndex:0];
userpath = [userpath stringByAppendingPathComponent:executableName];    // The file will go in this directory
NSString *saveFilePath = [userpath stringByAppendingPathComponent:@"db.sqlite"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager copyItemAtPath:[thisBundle pathForResource:@"db" ofType:@"sqlite"] toPath:saveFilePath error:NULL];
Run Code Online (Sandbox Code Playgroud)

但这不会复制任何东西,BTW这是一个Mac应用程序.

pme*_*ino 5

最后让它加入了

if ([fileManager fileExistsAtPath:userpath] == NO)
    [fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];
Run Code Online (Sandbox Code Playgroud)

结果代码是:

NSBundle *thisBundle = [NSBundle mainBundle];

NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *userpath = [paths objectAtIndex:0];
userpath = [userpath stringByAppendingPathComponent:executableName];    // The file will go in this directory
NSString *saveFilePath = [userpath stringByAppendingPathComponent:@"db.sqlite"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:userpath] == NO)
    [fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];

[fileManager copyItemAtPath:[thisBundle pathForResource:@"db" ofType:@"sqlite"] toPath:saveFilePath error:NULL];
Run Code Online (Sandbox Code Playgroud)