NSUserDefault未保存

NSUserDefault未保存

我只希望在尚未分配变量“genderDefault”的情况下显示警报。

这段代码是为了节省用户的选择:

func genderAlert()
    {
        let alertController = UIAlertController(title: "Quick Question", message: "What's your gender?", preferredStyle: UIAlertControllerStyle.Alert)
        let okAction = UIAlertAction(title: "Male", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        NSLog("Male Pressed")
            self.genderDefault.setValue("male", forKey: "gender")
        }
        let cancelAction = UIAlertAction(title: "Female", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        NSLog("Female Pressed")
            self.genderDefault.setValue("female", forKey: "gender")
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }

这是控制警报是否显示的if语句:
if(genderDefault != "male" || genderDefault != "female")
        {
            genderAlert()
        }

最佳答案

迅捷3

let genderDefault = UserDefaults.standard
genderDefault.set(value: AnyObject?, forKey: String) // SET
genderDefault.object(forKey: String)                 // GET

迅捷2
let genderDefault = NSUserDefaults.standardUserDefaults()
genderDefault.setObject("female", forKey: "gender")    // SET
if let gender = genderDefault.stringForKey("gender"){  // GET
    if((gender as! String) != "male" || (gender as! String) != "female")
    {
        genderAlert()
    }
}

关于ios - NSUserDefault未保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38862915/

10-13 02:59