【发布时间】:2014-04-08 23:06:04
【问题描述】:
如何编辑或更改值字符串:
在这个 plist 中,我需要在第 2 项的启用值中更改或设置“否”,我看到很多示例,但不起作用,或已弃用,或不使用 ARC,有什么想法或示例代码吗?请大家帮忙
EDIT#1:我试试这个(不工作)
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"List.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:CONTENT_DEFAULT ofType:PLIST];
[fileManager copyItemAtPath:sourcePath toPath:path error:nil];
}
NSArray* newContent = [[NSArray alloc]initWithContentsOfFile:path];
NSDictionary *Dict = [[NSDictionary alloc]initWithDictionary:[newContent objectAtIndex:2]];
[Dict setValue:@"NO" forKey:@"Enabled"];
[Dict writeToFile:path atomically:YES];
注意:不工作,它崩溃发送给我:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x15de7ff0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Enabled.', or Im wrong in something?
编辑 #2 新尝试
NSString *path = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"plist"];
NSString *savingPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSArray* newContent = [[NSArray alloc]initWithContentsOfFile:path];
NSMutableDictionary *Dict = [[NSMutableDictionary alloc]initWithDictionary:[newContent objectAtIndex:2]];
[Dict setValue:@"NO" forKey:@"Enabled"];
savingPath = [savingPath stringByAppendingPathComponent:@"Modified.plist"];
[Dict writeToFile:savingPath atomically:YES];
NSLog(@"newContent:%@",newContent);
NSArray *newnew = [[NSArray alloc]initWithContentsOfFile:savingPath];
NSLog(@"newnew:%@",newnew);
注意:现在给我打印一个崩溃:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (3) beyond bounds (2)'
【问题讨论】:
-
你怎么知道它不起作用?您不会在 Xcode 内置编辑器中看到更改。顺便说一句,它应该是
[newContent objectAtIndex:3],而不是 2。 -
感谢 Sergius,我确实编辑了有关崩溃的问题
-
变量 *dict 应该是
NSMutableDictionary。并尝试NSLogging它 - 用输出更新我们。 -
感谢 Sergius,现在不会崩溃,但不会更改我 plist 中的任何内容
-
I NSLogging but print me (null) 也许是路径,但我该如何解决这个问题?
标签: objective-c nsarray nsdictionary plist xcode5.1