Могу ли я вызвать функцию уведомления в таймере? - PullRequest
0 голосов
/ 24 сентября 2019

У меня есть func, который возвращает массив структур случайно сгенерированных криптовалют, а затем передает его в tableView.Задача: генерировать новые данные массива и обновлять tableView каждые 5 секунд.Я должен передать данные с уведомлением .

class Notificator {

    static let dataUpdateNotification = NSNotification.Name(rawValue: "tableViewUpdateNotification")


}

class Currencies {

    var currencyArray = [Quote]() 
    var newCurrencyArray = [Quote]()


        init() {

            let timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { timer in postNotification(notification: Notificator.dataUpdateNotification)}

        }

       func postNotification(notification:Notification) {

            let newCurrencyArray = currencyArray

            NotificationCenter.default.post(name: Notificator.dataUpdateNotification, object: newCurrencyArray)


        }

В tableView я создал наблюдателя

class CryptoTableViewController: UITableViewController {

    var quotes = Currencies().generateQuotes(count:8) 

    NotificationCenter.default.addObserver(self, selector: #selector(updateTableView), name: Notificator.dataUpdateNotification, object: nil)

    @objc func updateTableView(notification: Notification) {

            if let object = notification.object {

                if let newGeneratedData = object as? [Currencies] {

                    quotes = newGeneratedData

                    self.tableView.reloadData()

         }
        }
       }

У меня есть эта ошибка Невозможно преобразовать значениетипа «NSNotification.Name» к ожидаемому типу аргумента «Уведомление» Направляюсь ли я в правильном направлении или нет?

1 Ответ

2 голосов
/ 24 сентября 2019

A Notification.Name - это просто строка.Что вам нужно сделать, это создать уведомление, используя этот Name.В вашем методе postNotification(notification:) вы передаете String, а не Notification.

Попробуйте заменить этот код: postNotification(notification: Notificator.dataUpdateNotification) следующим: postNotification(notification: Notification(name: Notificator.dataUpdateNotification)).

Вам нужно передать Notification в этот метод, но вы передаете Notification.Name, который является String, а не Notification.

...