Передача параметров с помощью #selector

Я новичок в Swift и пытаюсь запустить функцию через NotificationCenter. Наблюдатель в ViewController.swift вызывает функцию reload:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(reload), name: NSNotification.Name(rawValue: "reload"), object: nil)
}

func reload(target: Item) {
    print(target.name)
    print(target.iconName)
}

... который имеет параметр класса Ítem:

class Item: NSObject {
    let name: String
    let iconName: String
    init(name: String, iconName: String) {
        self.name = name
        self.iconName = iconName
    }
}

Уведомление отправлено из «menu.swift»:

class menu: UIView, UITableViewDelegate, UITableViewDataSource {

let items: [Item] = {
    return [Item(name: "Johnny", iconName: "A"), Item(name: "Alexis", iconName: "B"), Item(name: "Steven", iconName: "C")]
}()

...

func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reload"), object: items[indexPath.row])
    }

Как присвоить значение объекта items[indexPath.row] из 'menu.swift' параметру функции reload в 'ViewController.swift'?


person nomadoda    schedule 27.03.2017    source источник


Ответы (1)


Если вы хотите передать объект классам, зарегистрированным в NotificationCenter, вы должны поместить его в .userInfo словарь объекта уведомления, который передается в функцию-наблюдатель:

NotificationCenter.default.addObserver(self, selector: #selector(reload), name: Notification(name: "reload"), object: nil)

--

let userInfo = ["item": items[indexPath.row]]
NotificationCenter.default.post(name: "reload", object: nil, userInfo: userInfo)

--

func reload(_ notification: Notification) {
  if let target = notification.userInfo?["item"] as? Item {
    print(target.name)
    print(target.iconName)
  }
}
person ozgur    schedule 27.03.2017
comment
Спасибо! Это правильный ответ! Наблюдатель, похоже, не принимает reload(_:) в качестве допустимого аргумента #selector, но вместо этого отлично работает #selector(reload). - person nomadoda; 28.03.2017