3

ドキュメント フォルダ内の 1 つのファイルを確認したい。このファイルがドキュメント フォルダに存在しない場合は、メイン バンドルからドキュメント フォルダにコピーします。私はこのコードとこのファイルをコピーするように書いていますが、ここで私の問題.....!!!! 私のファイルは .sqlite ファイル (データベース ファイル) であり、ドキュメント フォルダーにコピーすると、データが自分自身にありません!!!! どうして???このファイルがメインバンドルにあるときは、それ自体にデータがあります。

これは私のコードですが、なぜ機能しないのかわかりません!!!!

#define DataName @"mydatabase.sqlite"


- (void)viewDidLoad
{
    [self CopyDatabase];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (NSString*)DatabasePath
{
    NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DocumentDir = [Paths objectAtIndex:0];
    //NSLog(@"%@",DocumentDir);
    return [DocumentDir stringByAppendingPathComponent:DataName];

}

- (void)CopyDatabase
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:[self DatabasePath]];
    NSString *FileDB = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DataName];
    if (success)
    {
        NSLog(@"File Exist");
        return;
    }
    else
    {
        [fileManager copyItemAtPath:FileDB toPath:[self DatabasePath] error:nil];
    }

}
4

2 に答える 2

5

そのデータベースの古いバージョンが存在するため、ドキュメントフォルダーが更新されているとは思いません。次の方法でドキュメント ディレクトリを削除し、それを viewDidLoad の先頭に追加できます。

- (void)viewDidLoad
{
    [self purgeDocumentsDirectory];
    [self CopyDatabase];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)purgeDocumentsDirectory
{
    NSLog(@"Purging Documents Directory...");
    NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
        [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
    }
}
于 2013-08-30T14:02:44.457 に答える
2

これが私の解決策です

-(void) copytoDocument {
    NSString *openFile ;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

        NSString *pgnPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.text", @"100_Greatest_games"]];

        if ([fileManager fileExistsAtPath:pgnPath] == NO)
        {
            NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"100_Greatest_games" ofType:@"text"];
            [fileManager copyItemAtPath:resourcePath toPath:pgnPath error:&error];
            if (error) {
                NSLog(@"Error on copying file: %@\nfrom path: %@\ntoPath: %@", error, resourcePath, pgnPath);
            } 
    }
   }
于 2016-06-29T12:23:51.500 に答える