Passing parameters with #selector

2019-06-28 02:28发布

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条回答
Lonely孤独者°
2楼-- · 2019-06-28 02:56

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)
  }
}
查看更多
登录 后发表回答