2015-12-08 56 views
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: 
+0

什麼信息打印在'chooseFriend'? –

+1

你確定'friendChosen'在設置時不是零嗎? –

+0

嘗試使用'valueForKey(「usernameToMessageWith」)作爲?字符串'而不是'stringForKey(「...」)'並使用'setValue(value,forKey:「」)保存數據' – LinusGeffarth

回答

0

我與你的代碼測試,看不出問題NSUserDefaults

NSUserDefaults.standardUserDefaults().setObject("Vien", forKey: "usernameToMessageWith") 
    NSUserDefaults.standardUserDefaults().synchronize() 

和:

let receivedUsername = NSUserDefaults.standardUserDefaults().stringForKey("usernameToMessageWith")! as String 
    print("RECEIVED USERNAME:\(receivedUsername)") 

和日誌:

RECEIVED USERNAME:Vien 

所以我覺得在你的chooseFriend這個問題。你應該檢查這一行代碼:

let friendChosen = self.friends.objectAtIndex(requestIndex) as! String 
+0

chooseFriend正常工作,設置後我可以調用NSUserDefault。你能想到另一個可能不起作用的原因嗎? –