0
當按下按鈕時,我正在設置一個NSUserDefaults值,但是當視圖被轉換時,該值未被設置,並且沒有任何返回值。
代碼:
按鈕代碼NSUserDefaults在視圖之間被擦除
func chooseFriend(sender: UIButton) {
let requestIndex = sender.tag
let friendChosen = self.friends.objectAtIndex(requestIndex) as! String
NSUserDefaults.standardUserDefaults().setObject(friendChosen, forKey: "usernameToMessageWith")
NSUserDefaults.standardUserDefaults().synchronize()
print(">>\(NSUserDefaults.standardUserDefaults().stringForKey("usernameToMessageWith")! as String)")
self.performSegueWithIdentifier("toChat", sender: self)
}
下一頁查看代碼
override func viewDidLoad() {
super.viewDidLoad()
print("TRANSITIONED")
let receivedUsername = NSUserDefaults.standardUserDefaults().stringForKey("usernameToMessageWith")! as String
print("RECEIVED USERNAME:\(receivedUsername)")
refreshTable()
let swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "dismissKeyboard")
swipe.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipe)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
testLabel.text = ""
self.messages.addObject("Loading......")
}
OUTPUT:
TRANSITIONED
RECEIVED USERNAME:
什麼信息打印在'chooseFriend'? –
你確定'friendChosen'在設置時不是零嗎? –
嘗試使用'valueForKey(「usernameToMessageWith」)作爲?字符串'而不是'stringForKey(「...」)'並使用'setValue(value,forKey:「」)保存數據' – LinusGeffarth