0Pricing
Swift Academy · Lesson

Removing Observers Safely

Avoid leaks and crashes from stale observers.

Removing Observers Safely

Observers must be removed when no longer needed. A dangling observer can fire after its owner is gone, causing bugs or, with old APIs, crashes.

Why Removal Matters

Selector-based observers historically had to be removed in deinit to avoid messaging a deallocated object.

import Foundation

class Watcher: NSObject {
    override init() { super.init() }
    deinit { NotificationCenter.default.removeObserver(self) }
}
print("Removes itself on deinit")

All lessons in this course

  1. Posting and Observing Notifications
  2. Notification userInfo Payloads
  3. Removing Observers Safely
  4. The Observer Pattern Alternatives
← Back to Swift Academy