I am developing a macOS application. i have a problem with a tableView that load an array of products from a web server. The products are correctly received by the app (i see them in console). But i have these problems: 1) i can't see my products text descriptions in my tableView cells; 2) when i click on a single cell the app crash with this error message:
fatal error: Index out of range
Here is my code:
import Cocoa
import AppKit
class Controller: NSViewController {
@IBOutlet var tableViewa: NSTableView!
var products = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Table list"
tableViewa.reloadData()
}
override func viewDidAppear() {
reload()
tableViewa.backgroundColor = NSColor.red
tableViewa.allowsEmptySelection = true
tableViewa.gridColor = NSColor.red
}
func reload() {
products = []
tableViewa.reloadData()
tableViewa.backgroundColor = NSColor.red
Products.store.requestProducts{success, products in
if success {
self.products = products!
self.tableViewa.reloadData()
}else {
print("download failed")
}
self.tableViewa.reloadData()
}
}
extension MasterViewController: NSTableViewDataSource, NSTableViewDelegate {
func numberOfRows(in atableView: NSTableView) -> Int {
print("products number: \(products.count)")
return products.count
}
func tableViewSelectionDidChange(_ notification: Notification) {
let tas = IndexPath(item: products.count, section: 0)
let Cell = tableViewa.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"),owner: tas ) as! ProductCell
let product = products[(tas as NSIndexPath).item]//here crash my app
Cell.product = product
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return true
}
func tableView(_ tableView: NSTableView, cellForRowAt indexPath: IndexPath) -> NSTableCellView{
let Cell = tableViewa.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"),owner: indexPath ) as! ProCell
let product = products[(indexPath as NSIndexPath).item]
Cell.product = product
Cell.textField?.stringValue = array.item.1
return Cell
}
}