我有一个具有此结构的.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)插入/替换文本?

最佳答案

您的结构具有一个数组数组。


  [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,使其可变并在特定索引处添加或插入。如果要插入,请不要忘记检查索引是否不大于该数组的计数。

10-06 13:10