Home > front end >  What is the (Function) string in the dataSource array?
What is the (Function) string in the dataSource array?

Time:04-05

I am developing an application for Mac for the first time. I developed a demo about NSTableView, but why does the first row of NSTableColumn always display (Function)? There is a string (Function) my data source, why does this appear? Can someone help with this? Below is my code。

class ViewController: NSViewController {
     
     var scrollView : NSScrollView?
     var tableView : NSTableView?
     var dataSource = NSMutableArray {
         return NSMutableArray()
     }
     
     override func viewDidLoad() {
         super.viewDidLoad()
         view.wantsLayer = true
         view.layer?.backgroundColor = NSColor.red.cgColor
         self.setupUI()
         for i in 0...20 {
             let name = NSString(string: "dataType\(i)")
             dataSource.add(name)
         }
         tableView?.reloadData()
     }
     
     func setupUI() {
         
         scrollView = NSScrollView(frame: view.bounds)
         tableView = NSTableView(frame: scrollView!.bounds)
         let cellId = NSUserInterfaceItemIdentifier(rawValue: "cellId")
         let column = NSTableColumn(identifier: cellId)
         column.title = "dataSource1"
         tableView?.addTableColumn(column)
         
         let cellId1 = NSUserInterfaceItemIdentifier(rawValue: "cellId1")
         let column1 = NSTableColumn(identifier: cellId1)
         column1.title = "dataSource2"
         tableView?.addTableColumn(column1)
         
         tableView?.dataSource = self
         tableView?.delegate = self
         scrollView?.contentView.documentView = tableView
         view.addSubview(scrollView!)
     }
 }

 extension ViewController : NSTableViewDataSource, NSTableViewDelegate {
     
     func numberOfRows(in tableView: NSTableView) -> Int {
         return dataSource.count
     }
     
     func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
         return dataSource[row]
     }
 }

enter image description here

CodePudding user response:

The trouble is, in large part, that this phrase does not do what you think it does:

 var dataSource = NSMutableArray {
     return NSMutableArray()
 }

Owing to a quirk in the Swift language, that code creates an array consisting of one element which is a function whose body is the stuff in curly braces. So now the array's first element is a function, and that is what the output is trying to tell you.

However, you should not be using NSMutableArray in any case — or NSString, for that matter. So, simply change

var dataSource = NSMutableArray {
     return NSMutableArray()
}

To

var dataSource = [String]()

And change

let name = NSString(string: "dataType\(i)")

To

let name = "dataType\(i)"
  • Related