Home > Software engineering >  What exactly is the default NotificationCenter property?
What exactly is the default NotificationCenter property?

Time:02-01

I want to create an additional NotificationCenter instance to separate my internal notifications from system notifications. However, when I looked at the class implementation, I did not understand what I was looking at.

open class NotificationCenter : NSObject {
    open class var default: NotificationCenter { get }
}

Where is the getter? What does default exactly get? This is what I was expecting to see:

extension NotificationCenter {
    static let default = NotificationCenter()
}

Is the default property a static singleton that we just don't see and the getter is just returning it?

And to implement my own custom center, could I just declare it the following way?

extension NotificationCenter {
    static let custom = NotificationCenter()
}

CodePudding user response:

NotificationCenter.default gets the default NotificationCenter instance for your app, which is a singleton.

The iOS frameworks are not open source, so when you look at the definition of NotificationCenter.default you see the interface it exposes, not the implementation, which would probably look very much like the code you expected to see.

You can, indeed, create your own NotificationCenter instances using NotificationCenter()

  • Related