尊敬的专家朋友们:
嗨,我已经试了一整天了,但我尝试的似乎都不起作用。基本上,我想使用NSDefault保存一个字符串数组(最大值: 20,不是重量级的)。它保存,它加载正常,但不是当我在真实设备上按减号按钮关闭应用程序时。我在iPhone 4gs (iOS 6)上测试了它。
我试过了
[[NSUserDefaults standardUserDefaults] synchronize];
in both
`applicationWillTerminate:(UIApplication *)application` and
`applicationDidEnterBackground:(UIApplication *)application`但它并没有起作用。
注意:在NSLog中,只要我不在真实设备上的后台终止应用程序,我就可以从NSDefault中很好地返回这些值。
有人知道为什么吗?在此之前,非常感谢您。请附样品说明。
=========================编辑(添加代码):
我正在添加一些代码,希望它会更清晰,并希望有人能在这里真正帮助我。
提前谢谢。一些动作,然后
self.count = [NSNumber numberWithInt:[self.count intValue] + 1];
count is a NSNumber
NSData *count = [NSKeyedArchiver archivedDataWithRootObject:self.count];
[[NSUserDefaults standardUserDefaults] setObject:count forKey:@"count"];
[[NSUserDefaults standardUserDefaults] synchronize];
arrayForSavedKey is a NSMutableArray
[[NSUserDefaults standardUserDefaults] synchronize];
NSData *array = [NSKeyedArchiver archivedDataWithRootObject:self.arrayForSavedKey];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"arrayForSavedKeys"];在这两种情况下:
applicationWillResignActive:(UIApplication \*)applicationapplicationWillEnterBackground:(UIApplication *)application我尝试添加以下行[NSUserDefaults standardUserDefaults synchronize];为了检索数据,我让委托调用A类中的方法,如下所示: loadSavedData和unarchiving:
NSData *savedKeys = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayForSavedKeys"];<br>
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:savedKeys]];<br>
self.arrayForSavedKey = [[NSMutableArray alloc] initWithArray: array];<br>(里面只有几个NSStrings )
其中,我不对输出进行日志记录,只要我不用减号终止应用程序,一切都很好。(但对于真实的设备,我看不到来自NSLog的任何东西,因为一旦我关闭了应用程序,应用程序也将在xCode中停止运行)
我今天已经花了一整天了,我已经筋疲力尽了。请帮帮忙。
发布于 2013-06-26 07:49:53
applicationWillTerminate:只在几种非常特殊的情况下被调用,所以不用费心去使用它。
使用applicationWillEnterForeground:保存您的默认设置已经太晚了。
applicationDidEnterBackground:方法是调用[[NSUserDefaults standardUserDefaults] synchronize];的合适位置。这样,如果你的应用程序在后台被终止,默认设置已经被保存。
https://stackoverflow.com/questions/17309369
复制相似问题