0

cache.plistに読み取り/書き込みしたい

リソースフォルダに保存されている既存の事前作成されたplistファイルを読みたい場合は、次の手順を実行できます。

path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathWithComponent@"cache.plist"];
NSMutableDictionary *root = ...

でもそれならiPhoneから読みたいです。

できません。Resourcesフォルダーは読み取り可能です。

だから私は使用する必要があります:

NSDocumentDirectory, NSUserDomain,YES

では、plistファイルをドキュメントディレクトリの場所にプレインストールするにはどうすればよいですか?

したがって、起動時にplistファイルをコピーする乱雑なコードをいじくり回す必要がないことを意味します。(それが唯一の方法でない限り)。

4

3 に答える 3

1

最終製品

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Cache.plist"];


NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *giveCachePath = [documentsDirectory stringByAppendingPathComponent:@"Cache.plist"];


BOOL fileExists = [fileManager fileExistsAtPath:giveCachePath];

if (fileExists) {
    NSLog(@"file Exists");
}
else {
    NSLog(@"Copying the file over");
    fileExists = [fileManager copyItemAtPath:finalPath toPath:giveCachePath error:&error];
}

NSLog(@"Confirming Copy:");

BOOL filecopied = [fileManager fileExistsAtPath:giveCachePath];

if (filecopied) {
    NSLog(@"Give Cache Plist File ready.");
}
else {
    NSLog(@"Cache plist not working.");
}
于 2010-05-18T10:33:17.510 に答える
1

これが本当にあなたが求めているものではないことは知っていますが、私が知る限り、ドキュメントをDocumentsフォルダーに入れる唯一の方法は、実際にそこにコピーすることです...ただし、最初の起動時のみです。sqliteデータベースにも似たようなものを使用します。以下のコードは機能しますが、少しクリーンアップすることで実行できることに注意してください。

// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"WordsDatabase.sqlite3"];
    createdDatabaseOk = [fileManager fileExistsAtPath:writableDBPath];
    if (createdDatabaseOk) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"WordsDatabase.sqlite3"];
    createdDatabaseOk = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
}

AppDelegateを呼び出すだけです-本当に面倒ではありませんか?

于 2010-05-18T06:45:42.500 に答える
1

簡単。最初に、それがドキュメントディレクトリにあるかどうかを確認してください。そうでない場合は、アプリのResourcesフォルダー([[NSBundle mainBundle] pathForResource...])内で見つけて、を使用してドキュメントディレクトリにコピーし[[NSFileManager defaultManager] copyItemAtPath:...]ます。次に、ドキュメントディレクトリの新しいコピーを免責で使用します。

于 2010-05-18T06:45:59.790 に答える