Last active
November 19, 2015 01:33
-
-
Save matthewcheok/36bdc416fb3fa4bcba26 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class NotificationManager | |
{ | |
static let sharedManager = NotificationManager() | |
var observersMap = [String:NSHashTable]() | |
func add<T>(type: T.Type, observer: T) { | |
let typeString = "\(T.self)" | |
let observers: NSHashTable | |
// get the weak set of observers matching this type | |
if let set = observersMap[typeString] { | |
observers = set | |
} else { | |
observers = NSHashTable.weakObjectsHashTable() | |
observersMap[typeString] = observers | |
} | |
observers.addObject(observer as? AnyObject) | |
} | |
func make<T>(type: T.Type, @noescape closure: T -> Void) { | |
let typeString = "\(T.self)" | |
if let set = observersMap[typeString] { | |
for observer in set.allObjects { | |
closure(observer as! T) | |
} | |
} | |
} | |
} | |
protocol TestProtocol { | |
func hello() | |
} | |
class TestClass: TestProtocol { | |
let name: String | |
init(name: String) { | |
self.name = name | |
} | |
func hello() { | |
print("hello \(name)") | |
} | |
} | |
let object = TestClass(name: "First") | |
let object2 = TestClass(name: "Second") | |
NotificationManager.sharedManager.add(TestProtocol.self, observer: object) | |
NotificationManager.sharedManager.add(TestProtocol.self, observer: object2) | |
NotificationManager.sharedManager.make(TestProtocol.self) { (item) -> Void in | |
item.hello() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment