0

Since UITableView is in UIViewController, I made a class that conforms UITableViewDataSource protocol and attaches it to the table view in UIViewController's viewDidLoad() like below.

delegate for table view in UIViewTableController:

class TableViewController: NSObject, UITableViewDataSource, UITableViewDelegate {       
    var data

    // where should I do this task and how can i reload data after task? 
    data = asyncFuncToGetData() 

    // this is not working
    override init() {
        data = asyncFuncToGetData() 
    }

    func tableView() {
        // uses variable data
    }
}

UIViewController:

class ContainerViewController: UIViewController {
    @IBOutlet weak var mainTableView: UITableView!
    let delegate = TableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        mainTableView.dataSource = delegate
        mainTableView.delegate = delegate
    }
}

I have to fetch data from server because table needs it. So where should I do that? This can be done easily when UITableViewController conforms UITableViewDataSource protocol, but I do not want that way.

1
  • fetch data in viewDidLoad method. Commented Feb 22, 2018 at 4:46

1 Answer 1

1

You can fetch your data in ViewDidLoad and then feed it to your delegate:

override func viewDidLoad() {
    super.viewDidLoad()

    mainTableView.dataSource = delegate
    mainTableView.delegate = delegate

       asynFuncToGetData( { newData in
             //Assign New Data to your delegate class's data
             self.delegate.data = newData
             //Call Reload data on tableView's instance
             self.delegate.tableView()
       }  
}

Hope it helps!!

Sign up to request clarification or add additional context in comments.

1 Comment

I forgot that deletage is just a object. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.