7

iOS アプリを更新するときに、ディレクトリsqlite内の既存のデータベースを削除したいと考えています。Documents現在、アプリケーションの更新時に、データベースをバンドルからドキュメント ディレクトリにコピーし、バンドル バージョンを追加して名前を付けています。そのため、更新時に、存在する可能性のある古いバージョンも削除したいと思います。

sqliteループして以前のバージョンのファイルを探すことなく、すべてのファイルを削除できるようにしたいだけです。メソッドをワイルドカードするremoveFileAtPath:方法はありますか?

4

2 に答える 2

17

*.sqliteすべてのファイルを削除しますか? ループを回避する方法はありませんが、NSPredicate最初に a を使用して非 sql ファイルを除外し、高速な列挙を使用して高速なパフォーマンスを確保することでループを制限できます。これを行う方法は次のとおりです。

- (void)removeAllSQLiteFiles    
{
    NSFileManager  *manager = [NSFileManager defaultManager];

    // the preferred way to get the apps documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // grab all the files in the documents dir
    NSArray *allFiles = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];

    // filter the array for only sqlite files
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.sqlite'"];
    NSArray *sqliteFiles = [allFiles filteredArrayUsingPredicate:fltr];

    // use fast enumeration to iterate the array and delete the files
    for (NSString *sqliteFile in sqliteFiles)
    {
       NSError *error = nil;
       [manager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:sqliteFile] error:&error];
       NSAssert(!error, @"Assertion: SQLite file deletion shall never throw an error.");
    }
}
于 2013-02-12T16:55:51.733 に答える