Caleb Caleb - 3 months ago 29
iOS Question

NSUserDefault not being saved

I only want the alert to show up if the variable "genderDefault" has not been assigned yet.

This code is suppose to save the choice of the user:

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)
}


This is the if-statement that controls whether the alert shows up:

if(genderDefault != "male" || genderDefault != "female")
{
genderAlert()
}

Answer

Swift 3

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

Swift 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()
    }
}