0

この構造を持つ.plistファイルがありますが、

ここに画像の説明を入力

アイテム 5 を追加または置換したい。このコードを使用しています。

NSError *error ;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Introduction.plist"];

NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSString *comment = str;
[data replaceObjectAtIndex:1 withObject:comment];
[data writeToFile:path atomically:YES];

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"Introduction" ofType:@"plist"];
    [fileManager copyItemAtPath:bundle toPath:path error:&error];
}

それに変更replaceObjectAtIndex:する5と、plist 構造が変更されますが、それは望ましくありません。

特定のインデックスの行 5 (項目 5) にテキストを挿入/置換するにはどうすればよいですか?

4

1 に答える 1

4

構造体には配列の配列があります。

[data replaceObjectAtIndex:1 withObject:comment];

このコードでは、インデックス 1 の配列を文字列に置き換えています。特に 5 番目のインデックスに挿入する必要がありますか、それとも既存のサブ配列に追加するだけですか?

 NSMutableArray *subArray = [data[sectionIndex] mutableCopy];
if (!subArray) {
    subArray = [NSMutableArray array];
}

if (rowIndex<[subArray count]) {
    [subArray replaceObjectAtIndex:rowIndex withObject:comment];
}else{
    [subArray addObject:comment];
}

[data replaceObjectAtIndex:sectionIndex withObject:subArray];
[data writeToFile:path atomically:NO];

subArray にアクセスし、変更可能にして、特定のインデックスに追加または挿入します。挿入しようとしている場合は、インデックスがその配列のカウントよりも大きくないかどうかのチェックを含めることを忘れないでください。

于 2013-04-18T07:07:25.527 に答える