[英]How can I save an array of another view controller to the file within the app delegate?
I have an array in my root view controller that I need to save (using core data) whenever applicationDidEnterBackground
is called. 我的根视图控制器中有一个数组,每当调用applicationDidEnterBackground
都需要保存(使用核心数据)。 How can I send a message to an instance of the root view controller within the delegate? 如何将消息发送到委托中的根视图控制器实例?
I was thinking about giving the delegate a reference to view controller when it's set as the root, but that feels inefficient. 我正在考虑为委托提供对视图控制器的引用,但将其设置为根,但这感觉效率很低。 Is there a better way to do this? 有一个更好的方法吗?
In your root view controller register to receive the ApplicationWillEnterBackground notification. 在您的根视图控制器中注册以接收ApplicationWillEnterBackground通知。 The root view controller can then perform a save when it receives this notification. 根视图控制器可以在收到此通知后执行保存。
Your initial instinct to reduce coupling between controllers was a good one. 您最初的想法是减少控制器之间的耦合,这是一个很好的选择。
1) In your RootViewController .h file, 1)在您的RootViewController .h文件中,
+ (RootViewController *) sharedStore;
2) In your RootViewController .m file, 2)在您的RootViewController .m文件中,
+ (RootViewController *) sharedStore
{
static RootViewController *myStore = nil;
if (!myStore) {
myStore = [[RootViewController alloc] init];
}
return myStore;
}
3) Go to your AppDelegate.m file and import your RootViewController 3)转到您的AppDelegate.m文件并导入RootViewController
#import RootViewController.h
4) In your AppDelegate.m file, go to the ApplicationDidEnterBackground method and type: 4)在您的AppDelegate.m文件中,转到ApplicationDidEnterBackground方法并键入:
[[RootViewController sharedStore] saveChanges];
5) Implement the saveChanges method in RootViewController. 5)在RootViewController中实现saveChanges方法。
AJ112's answer makes: AJ112的答案是:
UIViewController
, which is not a good practice. 来自UIViewController
的单例,这不是一个好习惯。 UIApplication
, which is something to avoid as much as possible. 创建与UIApplication
耦合,这是尽可能避免的事情。 There are some UIApplication
notifications that you can observe from whatever class you need to handle multitasking. 您可以从处理多任务所需的任何类中观察到一些UIApplication
通知。 Check the answer on this SO question: 检查关于此SO问题的答案:
iphone 4 sdk : detect return from background mode iPhone 4 SDK:检测从后台模式返回
You can check all the notifications that UIApplication
posts in here: 您可以在此处检查UIApplication
发布的所有通知:
http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006728-CH3-DontLinkElementID_4 http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006728-CH3-DontLinkElementID_4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.