您可以使用NSFileManager檢查文件夾文件夾中是否已經存在文件,如果沒有,請移動它們。如果移動成功,則刪除舊文件並返回新路徑,否則返回舊路徑。見下:
...
NSString *mySQLfilePath = [self getFilePathWithName:@"database.sqlite"];
...
- (NSString *)getFilePathWithName:(NSString *)filename
{
NSString *libPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *fileLibPath = [libPath stringByAppendingPathComponent:filename];
NSString *fileDocPath = [docPath stringByAppendingPathComponent:filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:fileLibPath]) {
// file already exists in Library folder
return fileLibPath;
} else if ([[NSFileManager defaultManager] fileExistsAtPath:fileDocPath]) {
// file exists in Documents folder, so move it to Library
NSError *error = nil;
BOOL moved = [[NSFileManager defaultManager] moveItemAtPath:fileDocPath toPath:fileLibPath error:&error];
NSLog(@"move error: %@", error);
// if file moved, you can delete old Doc file if you want
if (moved) [self deleteFileAtPath:fileDocPath];
// if file moved successfully, return the Library file path, else, return the Documents file path
return moved ? fileLibPath : fileDocPath;
}
// file doesn't exist
return nil;
}
- (void)deleteFileAtPath:(NSString *)filePath
{
if ([[NSFileManager defaultManager] isDeletableFileAtPath:filePath]) {
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
NSLog(@"delete error: %@", error);
} else {
NSLog(@"can not delete file: %@", filePath);
}
}
如果您有任何疑問,請隨時與我們聯繫。而剛剛爲遊客參考:
https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html
你不能簡單地測試,如果該文件是在圖書館目錄,如果是這樣,在那裏使用它,如果它在文件目錄中移動它跨越,然後開始使用它?我不明白這個併發症。 – Droppy