Passing parameters with #selector

2019-06-28 03:13发布

问题:

I'm a beginner to Swift and I'm trying to initiate a function through NotificationCenter. The observer in 'ViewController.swift' calls on function 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)
}

... which has a parameter of class Ítem:

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

The notification is posted from "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])
    }

How do I assign the value of object items[indexPath.row] from 'menu.swift' to the parameter of function reload in 'ViewController.swift'?

回答1:

If you want to pass an object around classes that are registered to NotificationCenter, you should put that into .userInfo dictionary of notification object that is passed to observer function:

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)
  }
}