我只希望警报显示变量" 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()
}
答案 0 :(得分:4)
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()
}
}
答案 1 :(得分:0)
你要做的就是最后设置userDefaults.synchronize(),以便userDefaults知道现在必须保存
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue("female", forKey: "gender")
userDefaults.synchronize() // don't forget this!!!!