如何使用通知和访问userInfo?

皮佐塔

我正在Swift开发一个生活游戏项目。我需要将网格传递NotificationCenterView Controller我通过以下信息:

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

我收到NotificationViewController当我用以下命令打印出userInfo时:

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

我得到了(它适用于10x10网格,但我相信这足以回答我的问题):

网格(_cells:[[Assignment4.Cell(位置:(行:0,列:0),状态:Assignment4.CellState.empty),Assignment4.Cell(位置:(行:0,列:1),状态:Assignment4 .CellState.empty),Assignment4.Cell(位置:(行:0,col:2),状态:Assignment4.CellState.empty),Assignment4.Cell(位置:(行:0,col:3),状态:Assignment4 .CellState.empty),Assignment4.Cell(位置:(行:0,col:4),状态:Assignment4.CellState.empty),Assignment4.Cell(位置:(行:0,col:5),状态:Assignment4 .CellState.empty),Assignment4.Cell(位置:(行:0,col:6),状态:Assignment4.CellState.empty),

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

谢谢。

двп.петров

在通知处理功能中,您需要这样转换接收的数据:

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. 为了更轻松地访问自定义对象Grid,您可以创建带有2个与单元格数组匹配的参数的下标方法。EG:grid[x][y]可以翻译成grid.cells[x][y],这样细胞就可以变成private场。您可以在这里阅读更多内容

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章