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

时间:2011-08-11 16:15:05

标签: xcode cocoa macos 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];

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

2 个答案:

答案 0 :(得分:5)

最后让它继续添加

if ([fileManager fileExistsAtPath:userpath] == NO)
    [fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];

结果代码是:

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];

答案 1 :(得分:0)

您可能需要仔细检查文件路径:

NSLog(@"src: %@", [thisBundle pathForResource:@"db" ofType:@"sqlite"]);
NSLog(@"dst: %@", saveFilePath);