1

我正在开发一个具有“添加到书签/收藏夹”功能的 iphone 应用程序

但是这些书签中的每一个都有一个“状态”子标题或字段,“状态”在打开的 jSon 数据库中不断更新,因此在书签表视图中,当用户单击“更新”按钮时,它会向服务器并为每个书签提取最新的“状态”。

然后,当用户单击不同的视图时,它将所有新状态保存到 userDefault,我通过在“viewWillDisappear()”中执行以下操作来做到这一点:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myObject forKey:@"myServiceList"];
[defaults synchronize];

以上工作正常,数据已保存。

但是之后当我回到书签视图,然后再次单击其他视图时,它会崩溃!它不会通过以下代码行(因此它在第一次工作,但不是第二次):

[myDict setObject:[myService objectForKey:@"status"] forKey:@"status"];

在查看了 userDefault API 之后,我尝试添加以下代码行来解决问题,并且它工作得非常完美!

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myObject forKey:@"myServiceList"];
[defaults synchronize];
//I added the following
[NSUserDefaults resetStandardUserDefaults];

即使它解决了我的问题,但我真的不明白它是如何解决的,文档说它“同步对共享用户默认对象所做的任何更改并将其从内存中释放。”

这是否意味着我的“myServiceList”正在使用中,我必须先从内存中释放它才能再次使用它?

有人可以帮我理解这个问题吗?

谢谢你!

编辑:这是我的书签视图的viewWIllDisappear(),如果我从书签视图切换到其他视图,它会很好,然后当我回到书签视图并再次切换到其他视图时,它会崩溃:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSLog(@"start saving data");
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray * defaultArray = [[defaults objectForKey:@"myServiceList"] mutableCopy];
    for (NSString *key in self.tableContents) 
    {
        for(NSMutableDictionary *myService in [tableContents objectForKey:key])
        {
            for(NSMutableDictionary *myDict in defaultArray)
            {
                if([[myDict objectForKey:@"serviceNumber"] isEqualToString:[myService     objectForKey:@"serviceNumber"]])
                {
                    //The following line is where it will crash
                    [myDict setObject:[myService objectForKey:@"status"] forKey:@"status"];
                    NSLog(@"updated");
                    break;
                }
            }
        }
    }

    [defaults setObject:defaultArray forKey:@"myServiceList"];
    [defaults synchronize];
    //[NSUserDefaults resetStandardUserDefaults];
}
4

1 回答 1

0

I think what is happening is that by using resetStandardUserDefaults you have forced the flush from memory including serialising myObject.

My bet that if you haven't flushed it from memory, the in-memory copy of standardUserDefaults will try to return the original myObject which you gave it for the key "myServiceList".

If you trace things, I suspect that original myObject has either been corrupted somehow or deleted.

By forcing it to give you a fresh myObject, de-serialised back from disk, you are OK.

You could check this by hanging onto another copy of myObject, at the point at which you are calling resetStandardUserDefaults and then compare it with the value you get back for the key "myServiceList" later.

于 2014-11-14T08:09:03.250 回答