NSNotificationCenter removeObserver: in dealloc and thread-safety

前端 未结 3 1857
别跟我提以往
别跟我提以往 2021-02-03 14:12

I\'m using ARC and I\'m calling [[NSNotificationCenter defaultCenter] removeObserver:someObserver]; in observer\'s dealloc.

From NSNotification

3条回答
  •  无人及你
    2021-02-03 14:46

    Yes, NSNotificationCenter doesn't retain observer, but it still has a pointer to it in it's dispatch table.

    Q1: Quoting Apple docs

    Regular notification centers deliver notifications on the thread in which the notification was posted. Distributed notification centers deliver notifications on the main thread. At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center. For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.

    Q2,3: Yes.

    Q4,5: AFAIK it's safe unless you stumble into circular reference. I usually add/remove in -viewWillAppear:/-viewWillDisappear: for UIViewControllers and -init/dealloc for other classes.

提交回复
热议问题