Skip to content

Instantly share code, notes, and snippets.

@brentsimmons
Created September 8, 2016 16:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentsimmons/811151cd83c68a4fefbc6d7d30df412d to your computer and use it in GitHub Desktop.
Save brentsimmons/811151cd83c68a4fefbc6d7d30df412d to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Cocoa
// I’m trying to figure out how to add a Notification observer in Swift code where the notification name is defined in a .m file.
//
// This playground won’t actually run, because it assumes an NSString named SomeNotification defined in a .m file. So it can’t actually be used to see the errors. It’s just for illustration.
// The errors are listed in the comments.
class MyClass {
override init() {
super.init()
// Error: Cannot invoke value of type 'Notification.Name.Type' (aka 'NSNotification.Name.Type') with argument list '(rawValue: NSNotification.Name)'
NotificationCenter.default.addObserver(self, selector: #selector(somethingHappened(_:)), name: Notification.Name(rawValue: SomeNotification), object: nil)
// Error: Cannot convert value of type 'NSNotification.Name' to type 'String' in coercion.
NotificationCenter.default.addObserver(self, selector: #selector(somethingHappened(_:)), name: Notification.Name(rawValue: SomeNotification as String), object: nil)
// Error: Type 'NSNotification.Name?' has no member 'SomeNotification'
NotificationCenter.default.addObserver(self, selector: #selector(somethingHappened(_:)), name: .SomeNotification, object: nil)
}
dynamic func somethingHappened(_ notification: Notification) {
print("somethingHappened")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment