I'm trying to get results from a SQLite database, containing rows and columns, into a NSTableView, using Swift. There is no problem with the database query and I'm getting no errors when running the application. However, when displaying data, I always get the same (last) row in the table - repeated so many times as the total number of rows. What is missing in my code ? Thanks in advance.
`class SecondViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet var tableview: NSTableView!
var querySQL = ""
var bdadosDB: OpaquePointer?
var statement: OpaquePointer?
var allRows = [String]()
var rows = [String]()
var cols = [String]()
var CellIdentifiers :[String] = ["ordCell", "procCell", "espCell", "natCell", "recCell", "estCell", "julgCell", "decCell"]
override func viewDidLoad() {
let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let docsDir = dirPaths[0]
let databasePath = (docsDir as NSString).appendingPathComponent("bdados.db")
let dbpath = databasePath
sqlite3_open(dbpath, &bdadosDB)
querySQL = "SELECT * FROM proc"
sqlite3_prepare_v2(bdadosDB, querySQL, -1, &statement, nil)
while (sqlite3_step(statement) == SQLITE_ROW)
{
let str = String(sqlite3_column_int(statement, 0)) + ";"
let str_1 = String(cString: sqlite3_column_text(statement, 1)) + ";"
let str_2 = String(cString: sqlite3_column_text(statement, 2)) + ";"
let str_3 = String(cString: sqlite3_column_text(statement, 3)) + ";"
let str_4 = String(cString: sqlite3_column_text(statement, 4)) + ";"
let str_5 = String(cString: sqlite3_column_text(statement, 5)) + ";"
let str_6 = String(cString: sqlite3_column_text(statement, 6)) + ";"
let str_7 = String(cString: sqlite3_column_text(statement, 7))
let result = str + str_1 + str_2 + str_3 + str_4 + str_5 + str_6 + str_7
allRows.append(result)
}
let str_arr = allRows.joined(separator: "_")
rows = str_arr.components(separatedBy: "_")
tableview.dataSource = self
tableview.delegate = self
super.viewDidLoad()
}
func numberOfRows(in tableview: NSTableView) -> Int {
return rows.count
}
func tableView(_ tableview: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var text: String = ""
var cellIdentifier: String = ""
for i in 0 ..< rows.count {
let rw = rows[i]
cols = rw.components(separatedBy: ";")
for j in 0 ..< cols.count {
let col = cols[j]
if tableColumn == tableview.tableColumns[j] {
text = col
cellIdentifier = CellIdentifiers[j] }
}
}
if let cell = tableview.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier) , owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell }
else {
return nil }
}
}
`