xcode 如何在 AppDelegate 中使用 NSUserDefaults

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9745844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:40:45  来源:igfitidea点击:

How to use NSUserDefaults with AppDelegate

iosobjective-ciphonexcode

提问by user1214037

I am trying to use NSUserdefaults to save some data from a text field, I want it to be saved when the application quits and loaded when the application starts, however I have run into a wall.

我正在尝试使用 NSUserdefaults 来保存文本字段中的一些数据,我希望在应用程序退出时保存并在应用程序启动时加载它,但是我遇到了墙。

The methods that I want to use are all in the AppDelegate, Now I do not understand how to use AppDelegate very well, I have thought of two possible ways to achieve this, I have no idea if it would work though.

我想用的方法都在AppDelegate里面,现在不太明白AppDelegate怎么用,想了两种方法,不知道能不能用。

  1. Import AppDelegate and over ride the methods inside my VC OR
  2. create an instance of my VC in AppDelegate and allow AppDelegate to set and retrieve the text of my UITextField - (Don't this go against the MVC paradigm?)
  1. 导入 AppDelegate 并覆盖我的 VC 或内部的方法
  2. 在 AppDelegate 中创建我的 VC 实例并允许 AppDelegate 设置和检索我的 UITextField 的文本 - (这不违背 MVC 范式吗?)

Any suggestions would appreciated

任何建议将不胜感激

Thank you very much for your time

非常感谢您的宝贵时间

采纳答案by erkanyildiz

As you mentioned above you have two options:

如上所述,您有两种选择:

1-) Directly reach VC's UITextFieldfrom AppDelegate's applicationDidFinishLaunchingand applicationWillTerminatemethods.

1-)UITextFieldAppDelegate'sapplicationDidFinishLaunchingapplicationWillTerminate方法直接到达 VC 。

On applicationDidFinishLaunching:

applicationDidFinishLaunching

Read from NSUserDefaults, set UITextFieldin VC.

从 中读取NSUserDefaultsUITextField在 VC 中设置。

On applicationWillTerminate:

applicationWillTerminate

Read from UITextFieldin VC, set NSUserDefaultsand synchronize.

UITextFieldVC 中读取,设置NSUserDefaultssynchronize

2) Create proper methods in VC to do the same job and call them from AppDelegate.

2) 在 VC 中创建适当的方法来完成相同的工作并从AppDelegate.

-(void)record
{
// Read from UITextField, set UserDefaults and synchonize.
}

-(void)restore
{
// Read from UserDefaults, set UITextField.
}

回答by danh

Rather than keep the text field in your AppDelegate, keep the text. I'd do the following:

不要在 AppDelegate 中保留文本字段,而是保留文本。我会做以下事情:

1) In AppDelegate.h:

1) 在 AppDelegate.h 中:

@property (strong, nonatomic) NSString *textToBeSaved;

2) In AppDelegate.m, read and write textToBeSaved to NSUserDefaults when your app launches and terminates. On launch:

2) 在 AppDelegate.m 中,当您的应用程序启动和终止时,将 textToBeSaved 读取和写入 NSUserDefaults。启动时:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.textToBeSaved = [defaults objectForKey:@"save_me"];

and, before termination:

并且,在终止之前:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:self.textToBeSaved forKey:@"save_me"];
BOOL success = [defaults synchronize];

3) In SomeViewController.m that naturally owns the UITextField, in viewWillAppear:

3) 在 SomeViewController.m 中自然拥有 UITextField,在 viewWillAppear 中:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
myTextField.text = appDelegate.textToBeSaved;

4) When you set the textToBeSaved depends on your UI, but whenever you know the text is ready (say on textFieldShouldReturn, or shouldEndEditing), you can hand the string to AppDelegate:

4) 当您设置 textToBeSaved 时取决于您的 UI,但只要您知道文本已准备好(例如在 textFieldShouldReturn 或 shouldEndEditing 上),您就可以将字符串传递给 AppDelegate:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.textToBeSaved = myTextField.text;

If there's no UI to let the user accept the text, you can save the string on (textField:shouldChangeCharactersInRange:replacementString).

如果没有让用户接受文本的 UI,您可以将字符串保存在 (textField:shouldChangeCharactersInRange:replacementString) 上。

回答by Jamie

I would suggest you just register for some UIApplication notifications in your subclass and respond to them appropriately. Here is the link to the UIApplication docs. The notifications you can subscribe to are listed at the bottom of the page.

我建议你只在你的子类中注册一些 UIApplication 通知并适当地响应它们。这是 UIApplication 文档的链接。您可以订阅的通知列在页面底部。

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html

Here's an example of what you might do in your subclass:

以下是您可能在子类中执行的操作的示例:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         Selector:@selector(restore)
                                             name:UIApplicationDidFinishLaunchingNotification
                                          object :nil];

Don't forget to remove yourself as an observer as well. There are lots of tutorials online if you're not comfortable with NSNotifications.

也不要忘记将自己作为观察者移除。如果您对 NSNotifications 不满意,网上有很多教程。

回答by hotpaw2

It's certainly allowed to have the App Delegate hold a reference to the view controller chain. Apple's own examples and iOS app templates often put a pointer to a root view controller in an App Delegate instance variable.

当然允许 App Delegate 持有对视图控制器链的引用。Apple 自己的示例和 iOS 应用程序模板通常在 App Delegate 实例变量中放置一个指向根视图控制器的指针。

If the view controller chain is not broken, one possibility is to have the App Delegate send a "cleanUpNow" message to the top or root view controller, and have the view controllers pass that down the chain, with every view controller cleaning up as needed and then resending the message to all other controllers farther down the chain to clean up as well.

如果视图控制器链没有损坏,一种可能性是让 App Delegate 向顶部或根视图控制器发送“cleanUpNow”消息,并让视图控制器将其向下传递,每个视图控制器根据需要进行清理然后将消息重新发送到链中更远的所有其他控制器以进行清理。

Reaching directly into another view controller is probably less clean that sending it a message to clean up itself (write to NSDefaults etc.). Of perhaps have them all message a central "clean up" controller object whose purpose is to gather all the necessary state and write it out in one coherent chunk.

直接访问另一个视图控制器可能不如向它发送消息来清理自己(写入 NSDefaults 等)那么干净。也许让他们都向中央“清理”控制器对象发送消息,其目的是收集所有必要的状态并将其写在一个连贯的块中。

If the chain is broken, another option is for the App Delegate to send a notification, with any controllers needed to clean up registering handlers for that "clean up" notification.

如果链被破坏,另一个选择是让 App Delegate 发送通知,任何控制器都需要清理该“清理”通知的注册处理程序。