如何使用通知和访问userInfo?

时间:2018-07-23 04:56:42

标签: ios swift3 notifications nsnotificationcenter

我正在Swift开发一个生活游戏项目。我需要通过NotificationCenter将网格传递到View Controller。我正在传递信息,如下所示:

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

我在Notification中收到ViewController。当我使用以下命令打印出userInfo时:

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

我明白了(它适用于10x10网格,但我认为这足以回答我的问题):

  

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

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

谢谢。

2 个答案:

答案 0 :(得分:0)

杰克建议将其投射为网格类型:

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

答案 1 :(得分:0)

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

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上阅读更多内容。