是什么导致这种情况发生?这个错误的两个实例位于我的视图控制器的最底部,其中的行以“userDefaults”开头。这是我的代码
import UIKit
class SecondViewController : UIViewController,UITextFieldDelegate {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
var aRandomDate = NSDate()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerChanged(datePicker:UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
var strDate = dateFormatter.stringFromDate(datePicker.date)
dateLabel.text = strDate
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
@IBAction func Save(sender: UIButton) {
var t = EventSaver(pEventName: "Drinking Coffee", pEventDate: aRandomDate )
let encodedEventName = NSKeyedArchiver.archivedDataWithRootObject(t.EventName)
let encodedEventDate = NSKeyedArchiver.archivedDataWithRootObject(t.EventDate)
var encodedArray: [NSData] = [encodedEventName,]
userDefaults.setObject(encodedArray, forKey: "Event")
userDefaults.synchronize()
println("saved")
}
}
答案 0 :(得分:2)
似乎你还没有声明常量userDefaults。 在userDefaults中设置encodedArray对象之前添加以下行:
let userDefaults = NSUserDefaults.standardUserDefaults()
答案 1 :(得分:0)
像这样:
@IBAction func Save(sender: UIButton) {
var t = EventSaver(pEventName: "Drinking Coffee", pEventDate: aRandomDate )
var userDefaults = NSUserDefaults.standardUserDefaults()
let encodedEventName = NSKeyedArchiver.archivedDataWithRootObject(t.EventName)
let encodedEventDate = NSKeyedArchiver.archivedDataWithRootObject(t.EventDate)
var encodedArray: [NSData] = [encodedEventName,]
userDefaults.setObject(encodedArray, forKey: "Event")
userDefaults.synchronize()
println("saved")
}