肇鑫的技术博客

业精于勤,荒于嬉

苹果文档NotificationCenter中removeObserver(_:),讨论的部分是错误的

苹果的文档,在讨论中说:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method. Otherwise, you should call this method or removeObserver(_:name:object:) before observer or any object specified in addObserver(forName:object:queue:using:) or addObserver(_:selector:name:object:) is deallocated.

这里很容易被认为是说,对于iOS 9.0和macOS 10.11以上的系统,开发者没有必要再手动移除观察器了。但是我测试的结果却并非如此。

小实验

view controllers 2

假设两个视图控制器的关系如上图所示。点击上面的视图控制器的Show按钮,会弹出下面的视图控制器,然后点击发送通知按钮,会发送一个通知。代码如下:

import Cocoa

class ViewController: NSViewController {
    static let foo = Notification.Name("foo")

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func postNotificationButtonClicked(_ sender: Any) {
        NotificationCenter.default.post(Notification(name: ViewController.foo))
    }
}
import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [unowned self] (_) in
            
            print("foo!")
            self.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

测试步骤

  1. 运行应用
  2. 点击Show按钮
  3. 点击Post Notification按钮
  4. 关闭弹出的窗口。此时控制台会显示V2视图控制器完全退出。
  5. 点击Post Notification按钮。
  6. Xcode提示应用崩溃,因为V2视图控制器已经从内存中销毁了。没有想应的实例。

小结

虽然苹果说对于iOS 9.0和macOS 10.11之后的系统,开发者不必手动移除观察器。但是实际上,如果不移除,那么该观察器就是一直存在的,并有可能造成程序崩溃。

这是因为,NotificationCenter.defaultNotificationCenter的静态属性,它一直在内存中存在。注册在它上面的观察器,因此也就一直在内存中存在。

解决

方法1

在deinit中手动移除观察器。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200
    private var observer:NSObjectProtocol!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        observer = NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [unowned self] (_) in
            
            print("foo!")
            self.run()
        }
    }
    
    deinit {
        if let observer = self.observer {
            NotificationCenter.default.removeObserver(observer)
        }
        
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

方法2

使用[weak self]替代[unowned self]。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [weak self] (_) in
            
            print("foo!")
            self?.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

这个方法只能避免应用的崩溃。其余的代码还是会执行。如果你有涉及到存储之类的操作,这种方式可能并不适合。

方法3

NotificationCenter.default文档中,苹果说:

All system notifications sent to an app are posted to the default notification center. You can also post your own notifications there.

If your app uses notifications extensively, you may want to create and post to your own notification centers rather than posting only to the default notification center. When a notification is posted to a notification center, the notification center scans through the list of registered observers, which may slow down your app. By organizing notifications functionally around one or more notification centers, less work is done each time a notification is posted, which can improve performance throughout your app.

我尝试自建一个NotificationCenter的实例。这么做的原理是,既然类属性会一直存在,那么我们就不使用类属性,而是使用实例。实例应该在V2视图控制器销毁时自动销毁。

import Cocoa

class ViewController: NSViewController {
    static let foo = Notification.Name("foo")
    private weak var center:NotificationCenter? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func postNotificationButtonClicked(_ sender: Any) {
        center?.post(Notification(name: ViewController.foo))
    }
    
    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
        if segue.identifier == "showV2Segue" {
            let v2 = segue.destinationController as! V2ViewController
            center = v2.center
        }
    }
}
import Cocoa

class V2ViewController: NSViewController {
    private let a = 200
    var center  = NotificationCenter()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        center.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [unowned self] (_) in
            
            print("foo!")
            self.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

我万万没想到,这个方案居然失败了。我本以为NotificationCenter的实例会自动释放。但是实际上并没有。查看苹果的文档。我发现这么一段:

The block is copied by the notification center and (the copy) held until the observer registration is removed.

块被复制到通知中心,(这个复制品)一直存在,知道观察器被移除。

因此,这个其实和closure导致的循环引用是类似的。

方法4

方法3失败了。不过苹果的说明,启发了我对于方法4的尝试。addObserver(_:selector:name:object:)是添加观察器的另外一个方法,它本身不复制块,而是发送消息给指定对象的函数。这个方式很Objective-C。因此,它需要@objc属性的函数。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    @objc fileprivate func extractedFunc() {
        print("foo!")
        self.run()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(extractedFunc), name: ViewController.foo, object: nil)
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

这个方法才是符合苹果文档的描述的添加方式。
不过,从原理上讲。这个能够生效的原因,是因为addObserver(_:selector:name:object:)的第一个参数,即observer,它是将整个对象作为观察器,然后在需要时发送消息(第二个参数selector)给观察器。因此,当观察器(一般是当前的视图控制器)自动销毁时,就相当于给nil发送了一个消息。这种方式在Objective-C中是允许的,什么事情也不会发生。从理论上讲,这个其实是一种更安全的方法2。

方法5

搞懂了方法4,我们现在可以改进方法2。方法5,改进了方法2。能够达到方法4类似的结果。不过我们要始终记得,无论是方法2还是方法5,只要不采用方法1的方式移除观察器,那么被复制的块就会一直在等待被执行。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [weak self] (_) in
            
            guard let strongSelf = self else { return }
            
            print("foo!")
            strongSelf.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

总结

综合苹果的文档和实际测试的结果。不难发现,苹果文档存在错误。总结如下:

  1. 对于addObserver(_:selector:name:object:)添加的观察器。如果是iOS 9.0,macOS 10.11以后的系统,无需用户手动移除观察器。
  2. 对于addObserver(forName:object:queue:using:)添加的观察器。需要使用方法1或方法2的方法来解决。推荐使用方法1。
  3. 对于removeObserver(_:)文档。苹果的讨论是错误的。
  4. addObserver(_:selector:name:object:)的优点是不用手动注销观察器,缺点是需要单独创建一个函数,并且该函数必须是@objc的动态函数。
  5. addObserver(forName:object:queue:using:)的优点是无需单独创建函数,运行代码与添加代码紧密相连。缺点是每个控制器都需要单独用类变量记录下来,并且需要手动移除。(建议在deinit函数中移除)
  6. 综上,我认为方法4的方案是目前代价最小的方案。方法1是最完善的方案。方法5是最偷懒的方案。

closure导致的循环引用

最近在开发macOS版的咕唧2,遇到了视图控制器没有释放的问题。花了些时间进行调试。结果总结如下:

我们知道,如果存在循环引用,就会导致类无法释放。因此,我们通常会使用weak var delegate的方式来避免循环引用。

这里不谈一般的循环引用,谈谈closure的循环引用。

closure的循环引用

view controllers

如图,点击上面视图控制器的Next按钮,会自动弹出下面的视图控制器。代码如下:

import Cocoa

class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}
import Cocoa

class V2ViewController: NSViewController {
    private let a = 100
    private var foo:Foo!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        foo = Foo(doStaff)
        foo.run()
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    func doStaff() {
        print(self.a)
    }
}

class Foo {
    private(set) var bar:() -> ()
    
    init(_ bar:@escaping () -> ()) {
        self.bar = bar
    }
    
    deinit {
        print("Foo deinit.")
    }
    
    func run() {
        bar()
    }
}

运行并关闭弹出的视图控制器,控制台没有输出deinit的打印。存在内存泄漏。

分析

这是因为Foo中的bar,引用了V2ViewControllerdoStaff。而doStaff引用了self

解决

对于closure,我们不能使用weak,只能使用其它的方式。

方法1

调用完成后手动释放。

func run() {
    bar()
    bar = {}
}

方法2

还是手动释放,不过将bar定义为(()->())?,即Opitional

class Foo {
    private(set) var bar:(() -> ())?
    
    init(_ bar:@escaping () -> ()) {
        self.bar = bar
    }
    
    deinit {
        print("Foo deinit.")
    }
    
    func run() {
        bar?()
        bar = nil
    }
}

方法3

更改调用的方式,不直接分配函数,而是增加一层closure

override func viewDidLoad() {
    super.viewDidLoad()
    
    foo = Foo({ [unowned self] in
        self.doStaff()
    })
    
    foo.run()
}

通常我们认为直接分配和增加一层是等价的。但是这里我们看到,实际上,二者并不完全等价。

结论

综合起来,我认为方法3的解决方案,修改代码的成本是最低的。因为它是直接从源头解决了问题。

iOS每次升级后,苹果表表盘通知额度归零问题的处理

我是苹果表的老用户了。有多老?初代苹果表可以预购的第一天,我就预定了一只42mm的不锈钢苹果表。除了2018年苹果表电池把屏幕拱开,维修返厂的那几天,我天天都戴着它。

我写的应用,有一个叫Stand Minus的,提交到了苹果商店后,被审核的工作人员认为功能太少给拒绝上架了。我觉得它现有功能“增一分则肥,减一分则瘦”,拒绝修改。所以这个应用我就自己这一个用户。今天我要说的就是和这个Stand Minus相关的内容。

感谢git的存在,我们可以知道,Stand Minus是我在2017年1月31日最初创建的。

stand_minus_initiation

Stand Minus有两种工作方式,根据当前表盘是否有Stand Minus的小部件来判断。

发现问题

根据苹果的文档,当iOSwatchOS发送消息的时候,可以使用WCSession,其中最好用的方法是transferCurrentComplicationUserInfo(_:)。这个方法,同时还能唤醒手表端扩展的后台。因为能唤醒后台,会导致额外的耗电,所以苹果规定每天唤醒次数最多只能有50次,超过就自动变成不能唤醒后台的transferCurrentComplicationUserInfo(_:)调用。

一天有24小时,50次限制约等于每小时2次。我们可以使用remainingComplicationUserInfoTransfers属性来获得剩余的次数。

Stand Minus设计就是每小时发送两次,一天50次肯定是用不光的。但在实际使用中,有时候表盘小部件并没能及时更新。通过手表端查看我发现,提示剩余次数为0。

zero_count_remain

这个问题不常见,但是有时也会出。经过多次观察,我最终发现,这个问题和iOS升级有关,每次iOS升级完成之后,剩余次数都会归零。解决的办法很简单,额外再重启一次手机,然后就好了。

尝试解决问题

时光荏苒,到了2019年,因为升级到iOS 13 beta之后,我一直使用的推送OneSignal失效了。不得不重新折腾起一直用得好好的Stand Minus。同时,我尝试测试究竟是什么原因导致了次数归零。

我将代码

remainCountsLabel.text = String(session.remainingComplicationUserInfoTransfers)

改成了

remainCountsLabel.text = {
    guard session.activationState == .activated else {
        return "Session状态不是.activated。"
    }
    
    guard session.isWatchAppInstalled else {
        return String("对应手表应用正在安装中……")
    }
    
    guard session.isComplicationEnabled else {
        return "错误:手表当前表盘未安装Stand-的小部件。"
    }
    
    return String(session.remainingComplicationUserInfoTransfers)
}()

然后等待iOS的更新再测试。我最终发现了,导致错误的原因是,虽然手表的表盘上有Stand Minus的小部件,但是session.isComplicationEnabled返回的是否。而对于当前表盘没有对应小部件的情况下,session.remainingComplicationUserInfoTransfers返回0。

no_complication_erro

找到了更确切的原因,就可以解决问题了。我找了不用重启iPhone的办法。先切换手表的表盘到另外的表盘,然后再切回来,然后再点击Stand Minus的表盘小部件,打开手表应用。

经过上面的步骤,再重新打开手机上的应用查看,就会显示正确的剩余次数了。

最终解决方案

每次iOS升级之后,都做一遍切表盘,切表盘,开应用的操作。不算麻烦,但是也挺讨厌的。有没有有什么更好的办法呢?

我用的苹果表初代,在2018年的watchOS 5就不能更新了,我曾经猜测苹果应该早就修复了这个问题。我今年卖了苹果表5,手表到手之后,我发现苹果表5还是有这个问题。苹果怎么回事?这都watchOS 6了啊。

我尝试绕过这个问题。观察代码,手机向手表发送消息的核心代码如下:

if session.activationState == .activated && session.isPaired && session.isComplicationEnabled {
    session.transferCurrentComplicationUserInfo(userInfo)
}

即当一切正常,且当前表盘存在对应小部件的时候,发送能够唤醒后台的消息。已知出错的是session.isComplicationEnabled,那么可否移除它,直接发送唤醒后台的消息呢?

阅读文档,苹果是这么说的:

Call this method when you have new data to send to your complication. Your WatchKit extension can use the data to replace or extend its current timeline entries.

This method can only be called while the session is active—that is, the activationState property is set to WCSessionActivationState.activated. Calling this method for an inactive or deactivated session is a programmer error.

原来,调用transferCurrentComplicationUserInfo(_:)方法,只要求WCSession为活跃就可以,其余的都是可以忽略的。

于是我删掉了session.isComplicationEnabled的检测。这相当于主动忽略了系统出错的部分。

no_complication_but_still_send

不过,因为不再检测当前表盘是否存在小部件,相对于Stand Minus的原本架构,在不使用表盘小部件的情况下,手表的额外耗电理论上会多一些。

其它

我这边能做的就是这些。API的错误,最终还是需要苹果来解决。

参考资料