-1

我使用以下代码将值写入字典,但是当将新值添加到字典中时,它不会更新,它只显示最近添加的值的 plist,它也崩溃了。

nameString=nameTxt.text;
NSFileManager *mngr=[NSFileManager defaultManager];
NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath=[docDir objectAtIndex:0];
NSString *filePath=[docPath stringByAppendingPathComponent:@"score.plist"];
NSString *bundlePath=[[NSBundle mainBundle] pathForResource:@"score" ofType:@"plist"];

if ([mngr fileExistsAtPath:filePath]) {
    NSLog(@"File exists");
}
else {      
    NSLog(@"NO file exists");
    [[NSFileManager defaultManager] copyItemAtPath:bundlePath toPath:filePath error:NULL];      
}   

dict=[[NSMutableDictionary alloc]init];
dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];
NSLog(@"dict is %@",dict);
[dict setObject:nameString forKey:@"100"];
[dict writeToFile:filePath atomically:YES];

[dict release];

当我使用最后一行“[dict release]”时我崩溃了我的包中有一个 score.plist 文件。

4

2 回答 2

0

This is a simple memory problem.Along with solving the problem you have to understand the problem.

The dict is a NSMutableDictionary that you declared globally. And so that you can alloc it for using this so that you won't lose the scope of the dictionary.

So in the beginning say 'ViewDidLoad:' , you can alloc and init this as

dict=[[NSMutableDictionary alloc]init];

or in the present condition you can use like

dict=[[NSMutableDictionary alloc]initWithContentsOfFile: filePath];

So that you can alloc the dictionary with the score.plist file and everything will work fine.

What happended in your case is you alloced the dict. But in the next line you replace the alloced object of dict with autoreleaed object by the statement

dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

As the class methods always returns autoreleased objects, when you try to release the object which is autoreleased, it crashes. :-)

Hope you got the idea.

Now the solution is you can change the line

dict=[[NSMutableDictionary alloc]init];

To

dict=[[NSMutableDictionary alloc]initWithContentsOfFile: filePath];

And remove the line

dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

Everything will work. Happy Coding. :-)

于 2012-10-31T08:19:55.413 回答
0

崩溃是由于这条线,

dict=[[NSMutableDictionary alloc]init];
dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

第一行是分配内存,然后覆盖 dict 参数以链接到不属于您的静态字典。所以旧的被泄露了,当你释放它时,它会试图释放静态的。

而不是那种用途,

dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

并且不要使用发布声明。既然你不拥有它,你不必释放它。

检查这个

于 2012-10-31T06:47:01.747 回答