Skip to content

Instantly share code, notes, and snippets.

@naoty
Last active March 21, 2017 09:10
Show Gist options
  • Save naoty/ce52119333ccf252f05b0b42c7011704 to your computer and use it in GitHub Desktop.
Save naoty/ce52119333ccf252f05b0b42c7011704 to your computer and use it in GitHub Desktop.
import Foundation
class Observer: NSObject {
private let recipe: Recipe
init(recipe: Recipe) {
self.recipe = recipe
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func observe() {
NotificationCenter.default.addObserver(
self,
selector: #selector(receive(clipDidUpdateNotification:)),
name: Recipe.ClipNotification.didUpdate.name,
object: recipe
)
NotificationCenter.default.addObserver(
self,
selector: #selector(receive(clipDidRemoveNotification:)),
name: Recipe.ClipNotification.didRemove.name,
object: recipe
)
NotificationCenter.default.addObserver(
self,
selector: #selector(receive(clipDidAddNotification:)),
name: Recipe.ClipNotification.didAdd.name,
object: recipe
)
}
func receive(clipDidUpdateNotification: Notification) {
print("clip did update")
}
func receive(clipDidRemoveNotification: Notification) {
print("clip did remove")
}
func receive(clipDidAddNotification: Notification) {
print("clip did add")
}
}
class Recipe {
enum ClipNotification {
case didUpdate
case didRemove
case didAdd
var name: Notification.Name {
switch self {
case .didUpdate:
return Notification.Name("recipe.clip.didUpdate")
case .didRemove:
return Notification.Name("recipe.clip.didRemove")
case .didAdd:
return Notification.Name("recipe.clip.didAdd")
}
}
}
init(clip: Clip) {
self.clip = clip
}
var clip: Clip? {
didSet {
switch (oldValue, clip) {
case let (oldValue?, clip?) where oldValue != clip:
NotificationCenter.default.post(name: ClipNotification.didUpdate.name, object: self, userInfo: ["oldValue": oldValue, "clip": clip])
case let (oldValue?, nil):
NotificationCenter.default.post(name: ClipNotification.didRemove.name, object: self, userInfo: ["oldValue": oldValue])
case let (nil, clip?):
NotificationCenter.default.post(name: ClipNotification.didAdd.name, object: self, userInfo: ["clip": clip])
default:
break
}
}
}
}
struct Clip: Equatable {
let id: Int
static func == (left: Clip, right: Clip) -> Bool {
return left.id == right.id
}
}
let clip = Clip(id: 1)
var recipe = Recipe(clip: clip)
let observer = Observer(recipe: recipe)
observer.observe()
recipe.clip = nil // "clip did remove"
recipe.clip = Clip(id: 2) // "clip did add"
recipe.clip = Clip(id: 3) // "clip did update"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment