在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() } }
做下猜测:
1、error: memory read failed for 0x0。 0x0这个是被释放掉的对象,大意就是对象释放了然后还调用,所以出错了
2、deinit {
timer.invalidate() }
deinit相当于dealloc,应该是先去掉timer才会解除自身的循环引用,才会释放,才会调用deinit吧。感觉这里有点问题。在一个合适的时机,暂停timer,然后timer设为nil.看看这下行不行