Why willResignActiveNotification called multiple times with Collection view?

Viewed 451

I'm using PencilKit sample as an example. I added a willResignActiveNotification modification. After you quit move move back and fourth between collectionView and note 3 times.

Then move the app to background, you'll observe willResignActiveNotification active 3 times. I expect to see it called once only. But why 3 times? Is there a way to avoid it?

In DrawingViewController class, I have:

lazy var willResignActive: (Notification) -> Void = { [weak self] _ in
    print("Saved on willResignActive")
}

In viewWillAppear, I have

_ = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification,
                                           object: nil,
                                           queue:.main,
                                           using: willResignActive)

Here are the sample Xcode. https://github.com/legolasW/DrawingWithPencilKit To reproduce the result, click the note then back. Repeat. Then move the app to background, and you'll observe willResignActiveNotification runs multiple times.

The results are like below. enter image description here

Edits:

  • I tried to move addObserver to viewDidLoad, problem persists.

  • I tried to removeObserver in willResignActive closure, problem persists.

  • I double checked with the memory graph, can confirm its not a DrawingViewController memory retain.

  • I tried willResignActiveNotification, willResignActiveNotification, willBecomeActiveNotificication, willEnterBackground, showed same multiple call behavior.
1 Answers

Move

NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification,
                                       object: nil,
                                       queue:.main,
                                       using: willResignActive)

to viewDidLoad

Related