import UIKit class ViewController: UIViewController { let KEY_NAME = "inputData" @IBOutlet weak var inputText: UITextField! @IBOutlet weak var outputText: UITextField! var ud: NSUserDefaults = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. //初期化时取得首选项内容,并显示到output中 if var value: AnyObject = ud.objectForKey(KEY_NAME) { //命名为“inputData”的设定项存在的话设定 outputText.text = value as String } else { outputText.text = "设定项不存在" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func SaveText(sender: AnyObject) { //设定(保存)用户首选项 ud.setObject(inputText.text,forKey: KEY_NAME) } @IBAction func ClearText(sender: AnyObject) { //移除用户设定(保存)的首选项 ud.removeObjectForKey(KEY_NAME) } }