Objective c 在objective c中编辑文件

Objective c 在objective c中编辑文件,objective-c,plist,Objective C,Plist,我需要一个具有此结构的文件: 元素名称->值 元素名称->值 元素名称->值 因此,我将使用.plist文件。有时我想修改三个元素之一的值,我可以这样做吗? 或者我必须阅读整个文件并重写 欢迎使用任何其他解决方案。实际上,必须读取所有文件,以便对其进行解析并将其映射到内存中的正确结构 保存时,它也必须重写。我想完全读入文件,然后再写回将是最简单的 使用字典的示例: NSDictionary *myDictionary; NSMutableDictionary *mutableDict; NS

我需要一个具有此结构的文件:

  • 元素名称->值
  • 元素名称->值
  • 元素名称->值
因此,我将使用.plist文件。有时我想修改三个元素之一的值,我可以这样做吗? 或者我必须阅读整个文件并重写


欢迎使用任何其他解决方案。

实际上,必须读取所有文件,以便对其进行解析并将其映射到内存中的正确结构


保存时,它也必须重写。

我想完全读入文件,然后再写回将是最简单的

使用字典的示例:

NSDictionary *myDictionary;
NSMutableDictionary *mutableDict;
NSString *filePath;
NSNumber *numApplicationLaunches;
int intValue;

filePath = @"/your/path/here.plist";

/* Read in and make mutable copy */
myDictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];
mutableDict = [myDictionary mutableCopy];
[myDictionary release];

/* Edit necessary */
numApplicationLaunches = [mutableDict objectForKey:@"NumAppLaunch"];
intValue = [numApplicationLaunches intValue];
intValue++;
numApplicationLaunches = [NSNumber numberWithInt:intValue];
[mutableDict setObject:numApplicationLaunches forKey:@"NumAppLaunch"];

/* Write To file */
[mutableDict writeToFile:filePath atomically:YES];
[mutableDict release];
希望有帮助,
ief2有一个更简单的方法:

NSString *path =  [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSError *error = nil;
NSMutableArray *items = [NSPropertyListSerialization propertyListWithData:data
                                                       options:NSPropertyListMutableContainersAndLeaves
                                                        format:nil
                                                         error:&error];
当然,根据你的个人情况,你可能会得到一些不安全的东西。根据需要进行调整

数组中的所有对象(在所有深度)都是可变的。根据需要迭代/编辑,然后按照Henri的建议将其写出来