如何使用通知和访问用户信息?

How to use notification and accessing userInfo?

我正在 Swift 从事生命游戏项目。我需要通过 NotificationCenter 将网格传递给 View Controller。我传递的信息如下:

let nc = NotificationCenter.default
let info = ["grid": self.grid]
nc.post(name: EngineNoticationName, object: nil, userInfo:info)

我在 ViewController 中收到了 Notification。当我打印出 userInfo 时:

let grid = notified.userInfo?["grid"]
print("\(grid!)")

我明白了(它适用于 10x10 网格,但我相信这足以解决我的问题):

Grid(_cells: [[Assignment4.Cell(position: (row: 0, col: 0), state: Assignment4.CellState.empty), Assignment4.Cell(position: (row: 0, col: 1), state: Assignment4.CellState.empty), Assignment4.Cell(position: (row: 0, col: 2), state: Assignment4.CellState.empty), Assignment4.Cell(position: (row: 0, col: 3), state: Assignment4.CellState.empty), Assignment4.Cell(position: (row: 0, col: 4), state: Assignment4.CellState.empty), Assignment4.Cell(position: (row: 0, col: 5), state: Assignment4.CellState.empty), Assignment4.Cell(position: (row: 0, col: 6), state: Assignment4.CellState.empty),

如何访问此对象中的状态?

谢谢。

正如杰克建议的那样,将其转换为网格类型:

guard let grid = notified.userInfo?["grid"] as? gridType else {return}
//print(grid[0].state)

在您的通知处理函数中,您需要将收到的数据转换为:

func handleGridNotification(_ notification: Notification) {
    if let grid = notification.userInfo["grid"] as? Grid {
        print(grid.cells[0][0].state)
    }
}

以上代码应产生结果:Assignment4.CellState.empty

我还想在您的代码中附上两点:

  1. 数组中的单元格不应知道其索引。考虑离开网格来处理单元格索引的变化,或者换句话说你不需要这个:position: (row: 0, col: 1)
  2. 为了更轻松地访问您的自定义对象网格,您可以使用与单元格数组匹配的 2 个参数创建下标方法。例如: grid[x][y] 可以转换为 grid.cells[x][y] ,这样单元格就可以变成 private 字段。你可以阅读更多关于这个 here.