[英]NSUserDefault Value found nil with kill the App
我只是尝试在用户登录或向App注册时将用户ID和状态保存为UserDefaults
真实值。
UserDefaults.standard.set(user?.CustID, forKey: "CustID")
UserDefaults.standard.set(true, forKey: "status")
因此,当用户在我的Appdelegate
重新打开该应用程序时,我检查状态是否为true,然后用户直接通过HomeScreen
,如果状态为False,则其在登录屏幕上通过。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let status = UserDefaults.standard.bool(forKey: "status")
if (status == true) && (custID != "") {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "HomeTicketViewController") as! HomeTicketViewController
let navigationController = UINavigationController(rootViewController: nextViewController)
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.window!.rootViewController = navigationController
}else {
let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let navigationController = UINavigationController(rootViewController: nextViewController)
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.window!.rootViewController = navigationController
}
}
我的状态为true,但我发现The CustID
找到n。 有什么解决办法吗?
在userdefault
如果在与密钥对应的userdefaults
找不到值,则userdefault
返回nil
,如果是bool,则返回false
。
在您的情况下,当您启动应用程序时,应用程序没有与custID对应的任何值,因此您得到nil
。
您需要像这样添加支票
if (status == true) && (custID != nil){
:
:
}
默认为false
let status = UserDefaults.standard.bool(forKey: "status")
因此状态一开始将为false,状态为true并不意味着CustID
保存nil
UserDefaults.standard.set(user!.CustID, forKey: "CustID")
由于用户可能为零,因此请强制展开以验证
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.