在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
做下猜測:
1、error: memory read failed for 0x0。 0x0這個是被釋放掉的對象,大意就是對象釋放了然後還調用,所以出錯了
2、deinit {
timer.invalidate()
}
deinit相當於dealloc,應該是先去掉timer才會解除自身的循環引用,才會釋放,才會調用deinit吧。感覺這裡有點問題。在一個適當的時機,暫停timer,然後timer設為nil.看看這下行不行