2017-01-25 2 views
0

Wenn ich den folgenden Code verwenden:Mitteilung addObserver nicht mit Standard-Weise reagiert

override func viewDidLoad() { 
    nc = NotificationCenter.default 
    nc.addObserver(self, selector: #selector(self.receivedNotification), name:MyNotification, object: nil) 
}  


func receivedNotification() -> void { 
    NSLog("notification received") 
} 

receivedNotification nie

genannt Aber wenn ich die folgende Schließung Weise

verwenden
nc.default.addObserver(forName:MyNotification, object:nil, queue:nil) { 
    notification in 
     NSLog("notification received") 
} 

NSLog("...") ist erfolgreich namens.

Kann mir bitte jemand erklären, was hier geschieht

+0

NSNotificationCenter verwenden können. defaultCenter(). postNotificationName ("MyNotification", Objekt: nil) –

+0

self.receivedNotification sollte NameOfClass.receivedNotification sein – jarryd

Antwort

0

Empfangen (Get) Benachrichtigung

NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil) 

func methodOfReceivedNotification(notification: Notification){ 
     //Take Action on Notification 
} 

Send (Post) Benachrichtigung:

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil) 

Stopp hören Benachrichtigung

NotificationCenter.default.removeObserver(self, name: "NotificationIdentifier", object: nil); 
0

Bitte versuchen Sie den folgenden Code. Es ruft erfolgreich das nslog auf.

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    let nc = NotificationCenter.default 
    nc.addObserver(self, selector: #selector(self.receivedNotification), name:NSNotification.Name(rawValue: "MyNotification"), object: nil) 
} 


func receivedNotification() { 
    NSLog("notification received") 
} 

// um die Benachrichtigung zu schreiben

let nc = NotificationCenter.default 
    nc.post(name: NSNotification.Name(rawValue: "MyNotification"), object: nil) 
0

Sie diese Methode lokale Benachrichtigung genannt

override func viewDidLoad() { 
    nc = NotificationCenter.default 
    nc.addObserver(forName:MyNotification, object:nil, queue:nil, using:receivedNotification) 
} 

func receivedNotification() -> void { 
    NSLog("notification received") 
} 

zu erhalten und schreiben die Benachrichtigung

NotificationCenter.default.post(name: Notification.Name("MyNotification"), object: nil) 
Verwandte Themen