2011-08-11 89 views
2

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

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应用程序。

回答

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

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

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

好吧得到了它使用:if([fileManager fileExistsAtPath:userpath] == NO) [fileManager createDirectoryAtPat h:userpath withIntermediateDirectories:YES属性:nil error:nil]; – pmerino

+0

我有代码工作..但是有一个问题。假设文件大小为3.6 mb ..那么只有复制到文档目录的文件只有200kb ..它被部分复制。它有什么限制吗? –

相关问题