繁体   English   中英

发现NSUserDefault值无效并杀死该应用程序

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM