En Android, tenemos un objeto de datos en vivo mutable cuando lo actualizamos, digamos en un hilo diferente que le adjuntamos a un observador. Cuando el objeto se actualiza, el observador está escuchando y actualiza la interfaz de usuario en consecuencia.
liveDataService.setValue(response); ==> updating the object with new data
Y en la Actividad (digamos como TableViewController para swift/IOS)
Ponemos al observador
liveDataService.observeForever(s -> { Log.d(TAG, getString(R.string.service_observer_message)); updateUI(s); }); ==> When liveDataService changes we update the UI
Ahora quiero hacer lo mismo para Swift/IOS
veo la funcion
addObserver(_:forKeyPath:options:context:)
Pero no puedo adjuntarlo a un Array que recibe la actualización en segundo plano solo para NSObject
¿Cuál es el mejor método para realizar esta tarea?
gracias eran
Según tengo entendido, debe usar notificaciones locales para enviar datos con addObserver y postNotification para lograr esto. encuentre el código de muestra para el mismo.
let imageData:[String: UIImage] = ["image": image]
// publicar una notificación
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageData)
// Regístrese para recibir notificaciones en su clase
NotificationCenter.default.addObserver(self, selector: #selector(self.receiveData(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// manejar notificación
func receiveData(_ notification: NSNotification) { if let image = notification.userInfo?["image"] as? UIImage { } }
Puede usar la propiedad didSet observe. Responde cuando cambia el valor de la propiedad.
var dataArray = [String]() { didSet { print(“Array Count = \(dataArray.count)”) } }
cuando agrega datos en dataArray, llama a la propiedad dataArray, observe e imprima el Array Count
Hay varias formas de hacerlo.
El que más se acerque a su solución de Android debería ser Key Value Observing: https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift
Si desea leer más sobre ese tema: https://www.swiftbysundell.com/posts/observers-in-swift-part-1