在ViewController中使用自定义Notification处理applicationWillTerminate

在ViewController中使用自定义Notification处理applicationWillTerminate,第1张

概述Scenario:     希望在app退出时保存当前View中的UITextView的值,以便在app重新打开时显示用户退出前编辑的内容。 在AppDelegate的applicationWillTerminate中已经包含了保存NSUserDefaults的代码,仅需View在app退出时将UITextView的值保存在NSUserDefaults中。     首先考虑的是在ViewContr

Scenario:
    希望在app退出时保存当前VIEw中的UITextVIEw的值,以便在app重新打开时显示用户退出前编辑的内容。 在AppDelegate的applicationWillTerminate中已经包含了保存NSUserDefaults的代码,仅需VIEw在app退出时将UITextVIEw的值保存在NSUserDefaults中。
    首先考虑的是在VIEwController中通过接收处理系统的UIApplicationWillTerminateNotification来保存。于是有

Cocoa代码  

- (voID)saveCurrentValue {       // saving here   }      - (voID)vIEwDIDLoad {       [[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(saveCurrentValue) name:UIApplicationWillTerminateNotification object:nil];   }    

 

    但实际测试中发现并没能保存UITextVIEw的内容,通过NSLog调试才发现,原来在退出时,系统先执行了AppDelegate中的applicationWillTerminate,然后才执行VIEwController中的saveCurrentValue代码,所以无法保存内容。

解决方法:

    在AppDelegate的applicationWillTerminate中发送自定义的Notification,VIEwController中通过接收该自定义Notification处理保存内容的 *** 作,这样就可以保证在AppDelegate的保存 NSUserDefaults *** 作前先将内容保存。

#define kMyNotificationTerminate            @"MyNotificationTerminate"     Java代码  

//SampleAppDelegate.m   - (voID)applicationWillTerminate:(UIApplication *)application {       // post willterminate notification to allow vIEws to save current status       [[NSNotificationCenter defaultCenter] postNotificationname:kMyNotificationTerminate                                                            object:nil];          // Save changes.   }     //MySampleVIEwController.m   (voID)saveCurrentValue {   // saving value here   voID)vIEwDIDLoad {       [[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(saveCurrentValue) name:kMyNotificationTerminate object:nil];   voID)dealloc {       [[NSNotificationCenter defaultCenter] removeObserver:self name:kMyNotificationTerminate object:[UIApplication sharedApplication]];       [super dealloc];   }   总结

以上是内存溢出为你收集整理的在ViewController中使用自定义Notification处理applicationWillTerminate全部内容,希望文章能够帮你解决在ViewController中使用自定义Notification处理applicationWillTerminate所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1057789.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存