Search code examples
iosswiftdelegatesprotocolsdatasource

How create DataSource for my class like UITableDataSource?


I have a class GraphView(xib + class). Chart view with labels and other UI elements. I need to create DataSource protocol for this class it was realized in UITableView, as UITableDataSource. That needs for more comfortable working with data, which I want load to my GraphView.

If you know how do this or have link to this question solution, please help me. Thanks for all questions!


Solution

  • Creating a custom DataSource works just like a Delegate pattern.

    protocol GraphViewDataSource: class {
      func numberOfRow(for graph: GraphView) -> Int
    }
    
    class GraphView {
      weak var dataSource: GraphViewDataSource?
    
      init() {
        let numberOfRow = dataSource?.numberOfRow(for: self)
      }
    }
    

    Note: Don't forget to set your dataSource property to weak to avoid reference cycle (this is why GraphViewDataSource need to be constrained to class).