我已经在这个问题上挣扎了几天。我将播放器数据存储在由NSKeyedArchiver
创建的单个.plist文档中。在大多数情况下,一切都很好;但是,当我删除其中一个.plist文档时,将另一个加载到播放器对象中,并在应用程序通过NSKeyedArchiver
进入后台时激活-applicationDidEnterBackground:
,NSKeyedArchiver
重新创建已删除的.plist文件...所有旧数据都保持不变。另一方面,如果我从segue或任何其他方式调用完全相同的归档方法,它不会这样做。它从-applicationDidEnterBackground:
或-applicationWillTerminate:...
调用时重新创建文件,该文件不仅保存当前活动对象数据,而且还删除了已删除的文件(如果它是相同的对象,它应该被覆盖)到两个单独的文件
我在delete方法中尝试了campsObject=nil;
(我的播放器对象),但显然数据仍在内存中浮动。
所以,我的问题是,在NSKeyedArchiver
等使用-applicationDidEnterBackground
时,我应该注意哪些特殊内容?有什么想法吗?
在角色创建视图控制器上创建角色并传递给下一个:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//Initialize Camp object if not done already
if (!campsObject) {
campsObject = [[Camp alloc]init];
}
//Set up documents directory based on character name input
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
if ([_characterName.text isEqual:@""]) {
_characterName.text=@"Default Character";
}
NSString *savedFileName = [NSString stringWithFormat:@"%@.plist",_characterName.text];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:savedFileName];
//Check to see if file exists and unarchive it as campsObject
NSLog(@"Directory Checked for is %@",documentsDirectory);
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory]) {
NSLog(@"File exists!");
[self unArchiveObjects:self];
//[self screenUpdateKatalam];
}
else{
NSLog(@"File doesn't exist - will be created on exit, or backgrounding");
}
//Pass campsObject instance variable to next view controller
characterNameTextPassed=[NSString stringWithFormat:@"%@",_characterName.text];
NSLog(@"The character name passed will be %@",characterNameTextPassed);
ViewController *viewControllerInstance = [segue destinationViewController];
viewControllerInstance->campsObject=campsObject;
viewControllerInstance->documentsDirectory=documentsDirectory;
viewControllerInstance->characterNameTextPassed=characterNameTextPassed;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if ([title isEqualToString:@"Yes"]) {
[[NSFileManager defaultManager] removeItemAtPath: documentsDirectory error: nil];
[self hideAndDisableAllButtons];
campsObject=nil;
characterNamesArray=nil;
characterNameTextPassed=nil;
documentsDirectory=nil;
[self getCharacterNames:self];
[self refreshEntryScreen];
}
是删除方法(弹出的警告询问您是否确定要删除)
- (IBAction)archiveCampsObject:(id)sender {
NSLog(@"File will be saved to %@",documentsDirectory);
[NSKeyedArchiver archiveRootObject:campsObject toFile:documentsDirectory];
}
是归档对象的操作
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self archiveCampsObject:self];
NSLog(@"Background Saving Engaged!");
NSLog(@"Application going into the background");
}
是背景方法