在today widget里使用NSTimer,发生错误警报:error: memory read failed for 0x0
class TodayViewController: UIViewController, NCWidgetProviding {
var timer: NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
print("widget")
self.preferredContentSize = CGSizeMake(0,100);
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector(getBattery()), userInfo: nil, repeats: true)
}
func getBattery() {
print("level")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
deinit {
timer.invalidate()
}
}
高洛峰2017-04-18 09:25:04
Let’s make a guess:
1. error: memory read failed for 0x0. 0x0 is a released object. The general idea is that the object is released and then called, so an error occurs. 2. deinit {
timer.invalidate()
}
Deinit is equivalent to dealloc. The timer should be removed first before its own circular reference is released, and then deinit is called. I feel like there's something wrong here. At a suitable time, pause the timer, and then set the timer to nil. See if this works