【问题标题】:iPhone: How to copy a file from resources to documents?iPhone:如何将文件从资源复制到文档?
【发布时间】:2012-08-09 13:18:59
【问题描述】:

我刚开始开发 iPhone。在一个示例中,我必须在选项卡控制器的表格视图中显示存储在 sqlite db 中的一些数据,我必须将 sqlite 文件从应用程序包移动到文档文件夹。

我使用了应用程序模板 - iOS > 应用程序 > iPhone 的基于窗口的应用程序(使用核心数据进行存储)

在 XCode 生成的模板中(base sdk 设置为最新的 iOS = 4.2),有以下代码...

- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

在尝试获取文档文件夹的路径时,我使用了上面给出的方法......

NSString *documentDirectory = [self applicationDocumentsDirectory];

这给出了一个警告 - warning: incompatible Objective-C types initializing 'struct NSURL *', expected 'struct NSString *'

所以我把代码改成下面...

// Added the message absoluteString over here
NSString *documentDirectory = [[self applicationDocumentsDirectory] absoluteString];

NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"];
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
   NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}

然后砰!它给出了错误 - 'Failed to create writable database file with message 'The operation couldn’t be completed. No such file or directory'.'

我应该如何找到文档目录的路径,因为 XCode 模板生成的方法 applicationDocumentsDirectory 对我不起作用。

另外,有人可以对上面给出的applicationDocumentsDirectory 方法的目的有所了解。

谢谢

【问题讨论】:

  • 我收到错误,因为我没有在 writableDBPath 上添加文件名。这个例子帮助我修复它。谢谢! +1

标签: iphone


【解决方案1】:

这是一个简单的方法:

    NSFileManager *fmngr = [[NSFileManager alloc] init];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mydb.sqlite" ofType:nil];
    NSError *error;
    if(![fmngr copyItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/Documents/mydb.sqlite", NSHomeDirectory()] error:&error]) {
         // handle the error
         NSLog(@"Error creating the database: %@", [error description]);

    }
    [fmngr release];

【讨论】:

  • Rich 你是对的,但有点过时了。从当前文档:“这将始终返回文件管理器的相同实例。返回的对象不是线程安全的。在 Mac OS X v 10.5 及更高版本中,您应该考虑使用 [[NSFileManager alloc] init] 而不是单例方法defaultManager。使用 [[NSFileManager alloc] init] 代替,生成的 NSFileManager 实例是线程安全的。"
  • 所以,我将对上述内容进行一些小改动:我将第一行的 RHS 更改为 [[NSFileManager alloc] init],并添加 [fmngr release];在 if 块之后。
  • 感谢您指出这一点。我现在记得在 4.0 发布时读过它,但我想我只是把它塞进脑后,了解所有其他更新。
【解决方案2】:

几天前我自己也遇到了这个问题。不要强迫路径路径,拥抱 NSURL 路径。很快就会知道如何使用它们。

就方法而言,它只是要求系统将 URL 交给您应用程序的标准化文档目录。使用这个,几乎所有关于你放置新文件的地方都是正确的。

【讨论】:

  • 请提供更多详细信息? :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
  • 2011-05-02
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多