2011-08-11 90 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 ..它被部分複製。它有什麼限制嗎? –

相關問題