向列表中添加字符串类型的新键/值



我试图在iPhone上以编程方式添加新行到我的pList文件。但我不知道是怎么回事。我想添加键:someKey/类型:string/someevalue: string

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyPlist" ofType:@"plist"];
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
newArray = [NSArray arrayWithObjects:@"someKey", @"someValue", nil];
[plist setObject:newArray forKey:@"someKey"];
[plist writeToFile:path atomically:YES];
[plist release];

您不能修改应用程序包中的文件,这正是您上面的代码试图做的。

如果该文件应该是可修改的,则需要首先将其移动到documents文件夹中(例如,在第一次运行时),然后再对该文件夹进行读写。关于如何做到这一点有很多问题,例如:将plist复制到文档目录

键值编码可以使用NSDictionary:

// create dictionary
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
// add it to plist
[plist setObject:dict forKey:@"customDictionary"];

最新更新