Search code examples
iosswift3notificationsnsnotificationcenter

How to use notification and accessing userInfo?


I am working on a game of life project in Swift. I need to pass the grid via NotificationCenter to a View Controller. I am passing the info as follows:

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

I am receiving the Notification in the ViewController. When I print out the userInfo with:

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

I get (it goes on for the 10x10 grid but I believe this is enough for my question):

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

How can I access state in this object?

Thanks.


Solution

  • In your notification handling function, you need to cast the received data as so:

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

    The above code should produce result: Assignment4.CellState.empty

    I want also to adhere two things to your code:

    1. A cell within array should not know about its' index. Consider leaving the Grid to handle changes in cell indices, or in other words you do not need this: position: (row: 0, col: 1)
    2. For easier access to your custom object Grid you can create subscript method with 2 parameters matching the cells' array. E.G.: grid[x][y] could translate to grid.cells[x][y] , and this way cells could become private field. You can read more on this here.