如何删除 UserDefaults 数据 swift?

How to remove UserDefaults data swift?

userdaeults并没有删除内存中的数据,虽然我确实删除了。钥匙串进行删除。我分享下面的代码。它在退出时调用 handlelogout 函数。录音没问题,但是退出的时候并没有删除我保存的数据

 @objc func deleteee(){
        do {
            try keychain.remove("chipnumbernew")
        } catch let error {
            print("error: \(error)")
        }


    }

    @objc func deleteeetimer(){

        UserDefaults.standard.removeObject(forKey: "timertext")
        UserDefaults.standard.removeObject(forKey: "timertext2")
        UserDefaults.standard.synchronize()

    }
 @objc func handleLogout(){

        do {
            deleteee()
            deleteeetimer()
            try Auth.auth().signOut()



            let mainTableVC = LoginViewController()

            let navController = UINavigationController(rootViewController: mainTableVC)

            self.present(navController, animated: true, completion: {

                //
            })

        } catch let signOutError as NSError {
            print ("Giriş Yapılamadı: %@", signOutError)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let token = try? keychain.getString("chipnumbernew")
        chip1InfoString = token

        if let strtimer = UserDefaults.standard.string(forKey: "timertext") {
            print("strtimer", strtimer)
          timertextNew.text = strtimer
        }

        if let strtimer2 = UserDefaults.standard.string(forKey: "timertext2") {
            print("strtimer2", strtimer2)
            timertext2New.text = strtimer2

        } }

UserDefaults中的removeObject本身会清除该值。您可以直接在 plist 中进行验证。请参阅 this post 以访问 plist。

仍然,你想清理,你可以试试下面的代码。

    if let appDomain = Bundle.main.bundleIdentifier {
        UserDefaults.standard.removePersistentDomain(forName: appDomain)
    }