Advertisement
HXXXXJ

Notification center - BLOCK

Mar 11th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.33 KB | None | 0 0
  1. typealias block = () -> ()
  2.  
  3. class NotificationCenter {
  4.     static let shared = NotificationCenter()
  5.     var map :[String: [(AnyObject, block)]]
  6.  
  7.     private init(){
  8.         map = [String: [(AnyObject, block)]]()
  9.     }
  10.  
  11.     func addObserver(_ event: String, _ handle : @escaping block, _ target: AnyObject){
  12.         let pair = (target, handle)
  13.         map[event, default:[(AnyObject, block)]()].append(pair)
  14.     }
  15.    
  16.     func postEvent(_ event: String){
  17.         if let list = map[event]{
  18.             for pair in list {
  19.                 pair.1()
  20.             }
  21.         }
  22.     }
  23.    
  24.     func removeObserver(_ event: String, _ target: AnyObject) {
  25.         if let list = map[event]{
  26.             map[event] = list.filter{  $0.0 !== target}
  27.         }
  28.     }
  29.  
  30. }
  31. class obj {
  32. }
  33.  
  34.    
  35. let o1 = obj()
  36. let o2 = obj()
  37.  
  38. NotificationCenter.shared.addObserver("event1", {
  39.     print("obj1 - event 1")
  40. }, o1)
  41.  
  42. NotificationCenter.shared.addObserver("event1", {
  43.     print("obj2 - event 1")
  44. }, o2)
  45.  
  46. NotificationCenter.shared.addObserver("event2", {
  47.     print("obj2 - event 2")
  48. }, o2)
  49.  
  50.  
  51. NotificationCenter.shared.postEvent("event1")
  52. NotificationCenter.shared.postEvent("event2")
  53. print()
  54. NotificationCenter.shared.removeObserver("event1", o1)
  55. NotificationCenter.shared.postEvent("event1")
  56. NotificationCenter.shared.postEvent("event2")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement