This is code from a sample Swift Playground that shows how to do this. The Playground needs to have access to MPWFoundation, for example by being inside a Xcode workspace that includes it.
import Foundation
import MPWFoundation
@objc protocol ModelDidChange:MPWNotificationProtocol {
func modelDidChange( payload:NSNotification );
}
class MyView : NSObject,ModelDidChange {
override public init() {
super.init()
self.installProtocolNotifications()
}
func modelDidChange( payload:NSNotification ) {
print("I was notified, self: \(self) payload: \"\(payload.object!)\"")
}
}
let target1 = MyView()
let target2 = MyView()
sendProtocolNotification( ModelDidChange.self , "The Payload")
A brief walkthrough:
- We declare a
ModelDidChangenotification protocol. - We indicate that it is a notification protocol by adopting
MPWNotificationProtocol. - The notification protocol has the message
modelDidChange - We declare that
MyViewconforms toModelDidChange. This means we declaratively indicate that we receive ModelDidChange notifications, which will result in MyView instance being sentmodelDidChange()messages. - It also means that we have to implement
modelDidChange(), which will be checked by the compiler. - We need to call
installProtocolNotifications()in order to activate the declared relationships. - We use
sendProtocolNotification()with the Protocol object as the argument and a payload. - The fact that we need a protocol object instead of any old String gives us additional checking.

No comments:
Post a Comment