【问题标题】:Copy a file from the app bundle to the user's Application Support folder将应用程序包中的文件复制到用户的应用程序支持文件夹
【发布时间】:2011-10-25 03:38:39
【问题描述】:

我正在制作一个应用程序,我需要将某些文件从应用程序包复制到用户的应用程序支持文件夹。这是我实际使用的代码:

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

但这并没有复制任何东西,顺便说一句,这是一个 Mac 应用程序。

【问题讨论】:

    标签: xcode cocoa macos nsfilemanager


    【解决方案1】:

    终于搞定了

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 好的,可以使用:if ([fileManager fileExistsAtPath:userpath] == NO) [fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];
      • 我已经让代码工作了。但是有一个问题。假设文件大小为 3.6 mb.. 那么只有复制到文档目录的文件只有 200kb.. 它被部分复制。有什么限制吗??
      猜你喜欢
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2013-06-30
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多