Avatar ·

Cómo usar correctamente NSNotificationCenter (addObserver) en Swift: analizando la sintaxis y la cancelación de suscripción

¡Hola! Acabo de empezar a aprender Swift y estoy intentando implementar el intercambio de datos entre dos ViewController a través de NSNotificationCenter. En Objective-C vi esta sintaxis: ```objc [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"MyNotification" object:nil]; ``` Pero en Swift me confundí. Intento escribirlo así: ```swift NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: "MyNotification", object: nil) ``` Pero Xcode se queja del selector — dice que debo usar #selector. Lo reescribí: ```swift NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(handleNotification), name: "MyNotification", object: nil) ``` Pero ahora no entiendo cómo declarar correctamente el método handleNotification. ¿Debe aceptar un Notification? Y además: he oído que es obligatorio cancelar la suscripción a las notificaciones, de lo contrario habrá una fuga de memoria. ¿Cómo se hace correctamente en Swift? Muéstrenme,