我想从plist文件中检索一个整数,对其进行递增,然后将其写回到plist文件中。在“Levels.plist”文件中,一行包含关键字LevelNumber
,值1
。
我使用以下代码来检索值:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels.plist" ofType:@"plist"];;
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);
运行此命令时,控制台输出为0。有人可以告诉我我做错了吗?
最佳答案
NSString *filePath = [[NSBundle mainBundle]
pathForResource:@"Levels.plist" ofType:@"plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
initWithContentsOfFile:filePath];
lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);
我的猜测是,除非您实际上已将文件命名为“Levels.plist.plist”,否则NSBundle会为
pathForResource:ofType:
调用返回nil。请记住,如果该方法恰巧返回
nil
,则其余代码仍可以继续。给定nil
文件路径,NSMutableDictionary
将返回nil,随后将对象从字典中移出的调用也将返回nil
,因此您的日志记录调用显示输出为0。
关于ios - 写入plist文件而不写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11553226/