2011-01-20 132 views
10

我刚开始使用iPhone开发。在其中一个示例中,我必须在tabbar控制器的表视图中显示一些存储在sqlite数据库中的数据,我必须将sqlite文件从应用程序包移动到documents文件夹。iPhone:如何将文件从资源复制到文档?

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

在通过的XCode(基SDK设置为最新的iOS = 4.2)生成的模板,下面的代码在那里......

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

在试图让文档文件夹的路径,我用上面这样给出的方法...

NSString *documentDirectory = [self applicationDocumentsDirectory]; 

这给给出警告NG - 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方法的目的。

谢谢

+0

我得到的错误,因为我没有在writableDBPath添加的文件名。这个例子帮助我修复它。谢谢! +1 – voghDev 2014-11-26 11:52:16

回答

5

我刚刚在几天前遇到了这个问题。不要强制路径下的东西,包含NSURL路径。如何使用它们不需要很短的时间。

至于方法,它只是要求系统提交一个URL到应用程序的标准化文档目录。使用这个和大多数关于您放置新文件的位置都是正确的。

+0

更多详情请点击这里? :( – 2014-11-07 09:57:32

20

继承人一个简单的方法来做到这一点:

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

Rich你是对的,但有点过时从目前的文档:“这将始终返回文件管理器的相同实例。返回的对象不是线程安全的。 在Mac OS X v 10.5和后来你应该考虑使用[[NSFileManager alloc] init]而不是singleton方法defaultManager。使用[[NSFileManager alloc] init]来代替,所得到的NSFileManager实例是线程安全的。“ – 2011-01-22 22:18:20

相关问题