How to access and refresh a UITableView from another class in Swift

后端 未结 4 515
清歌不尽
清歌不尽 2021-01-03 09:24

I have a tab bar application and a tab whose view controller is controlled by a UITableView class. I have a class that is used to download data from the server that then sav

4条回答
  •  心在旅途
    2021-01-03 10:23

    You can use protocol or NSNotificationCenter

    Example of NSNotificationCenter :

    From the UIViewController that downloads the data, you can post a notification after finishing downloading the data and tell other objects that there is new data:

    NSNotificationCenter.defaultCenter().
                        postNotificationName("newDataNotif", object: nil)
    

    And any other object that wants to listen to this notification should register to observe (in your case the UITableViewController):

    NSNotificationCenter.defaultCenter().
                         addObserver(self, #selector(shouldReload), 
                         name:"newDataNotif", object: nil)
    

    and then you need to implement the method to be called when receive the notification:

    func shouldReload() {
      self.tableView.reloadData()
    }
    

    Note that the notification can send data also of type [NSObject : AnyObject]? example:

    NSNotificationCenter.defaultCenter().
                         postNotificationName("newDataNotif", 
                         object: nil, userInfo: ["data":[dataArray]])
    

    And the observer will be like:

    NSNotificationCenter.defaultCenter().
                         addObserver(self, #selector( shouldReload(_:)),
                         name:"newDataNotif", object: nil)
    

    And the method like:

    func shouldReload(notification:NSNotification) {
      println(notification.userInfo)
    }
    

    and finally in your deinit you should remove observer :

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

提交回复
热议问题