2

当我从屏幕返回并再次进入屏幕时,即使我删除了目标nextTrackCommand,也会多次调用目标viewWillDisappear。我做错了什么?

override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.shared.beginReceivingRemoteControlEvents()

    MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { [unowned self] (_) -> MPRemoteCommandHandlerStatus in
        print("go to next track")
        return .success
    }
}

override func viewWillDisappear(_ animated: Bool) {
    MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(self)
}
4

1 回答 1

7

您正在调用的重载addTarget不会添加self为目标。它添加了一个NSObject您以前不知道的对象作为目标。它返回这个对象。所以如果你想删除它,你应该得到它的返回值,把它保存在一个属性中,这样你就可以将它传递给removeTarget.

调用addTarget(handler:)方法添加要调用的块。通过调用removeTarget(_:)方法删除处理程序,传入此方法返回的对象。

var target: NSObject?
override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.shared.beginReceivingRemoteControlEvents()

    target = MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { [unowned self] (_) -> MPRemoteCommandHandlerStatus in
        print("go to next track")
        return .success
    }
}

override func viewWillDisappear(_ animated: Bool) {
    MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(target)
}

或者,调用实际上允许您添加为目标的其他重载。self

于 2020-11-29T01:10:34.867 回答