xcode 在 viewDidLoad 之前运行什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13439008/
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
What runs before viewDidLoad?
提问by Edward Hasted
I need to set and store some NSUserDefaults data that can be used withing a View. This doesn't work using viewDidLoad.
我需要设置和存储一些可以与视图一起使用的 NSUserDefaults 数据。这在使用 viewDidLoad 时不起作用。
Can this be done? What method could I use before viewDidLoad? What would you recommend?
这能做到吗?在 viewDidLoad 之前我可以使用什么方法?你会推荐什么?
回答by Edward Hasted
There are a couple of methods on UIViewController
that will definitely get run before viewDidLoad
- which is the appropriate place for your code depends on your specific problem and architecture.
有几种方法UIViewController
肯定会在之前运行viewDidLoad
- 代码的合适位置取决于您的特定问题和架构。
initWithNibName:bundle:
is called when the view controller is createdloadView
is the code that sets up the view
initWithNibName:bundle:
创建视图控制器时调用loadView
是设置视图的代码
Another option is to ensure that the defaults are set up by a different component, before your view controller is even initialised. That could be in the view controller of a preceding part of the workflow, or initialised by the application delegate.
另一种选择是确保在您的视图控制器甚至初始化之前由不同的组件设置默认值。这可能在工作流前面部分的视图控制器中,或者由应用程序委托初始化。
回答by Daij-Djan
applicationDidFinishLaunching sounds like a good place for defaults
applicationDidFinishLaunching 听起来像是默认设置的好地方
回答by Deekshith Bucky
This is an example to persist the login state of the application using UserDefaults:
这是使用 UserDefaults 保持应用程序登录状态的示例:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// You can keep your Google API keys here(if you have any)
let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
let homeScreen = storyBoard.instantiateViewController(withIdentifier: "YourHomecontroller") as? ViewController
if(UserDefaults.standard.isLoggedIn()){
self.window?.rootViewController = homeScreen
}else{
let loginScreen = storyBoard.instantiateViewController(withIdentifier: "LoginViewController")
self.window?.rootViewController = loginScreen
}
return true
}
And extend UserDefaults with these methods:
并使用以下方法扩展 UserDefaults:
// this is used to serialize the boolean value:isLoggedIn
func setIsLoggedIn(value:Bool){
setValue(value, forKey: "isLoggedIn")
UserDefaults.standard.synchronize()
}
// this method is used to check the value for isLoggedIn flag
func isLoggedIn() -> Bool{
return bool(forKey: "isLoggedIn")
}
this way, you can switch between the view controllers conditionally. if user is authenticated already you would want to show the home screen.
这样,您可以有条件地在视图控制器之间切换。如果用户已经过身份验证,您会想要显示主屏幕。
回答by baliman
Try it in your AppDelegate of your app
在您的应用程序的 AppDelegate 中尝试