在某些数据发生变化后如何刷新TableView?

时间:2017-06-12 17:32:13

标签: arrays swift uitableview

我想只在一个名为Network的类中更改用户列表。我不明白在userList发生变化后如何进行TableView更新。我将在下面的代码中向您展示一个示例和详细问题。

// Network.swift
class Network {
    var userList: [User] = []

    // Next functions may change userList array
    // For example, the data came from the server, and update the userList with new data
}

// App delegate
class AppDelegate: UIResponder, UIApplicationDelegate {
    var network: Network = Network()

    ..
}

// File TableViewController.swift
class TableViewController: UITableViewController {
    …
    var userList: [User] = [] // Here I want to have a full copy of the array from Network class

    override func viewDidLoad() {
        super.viewDidLoad()

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        self.userList = appDelegate.network.userList // Just copy an array
        // And I want that after each update appDelegate.network.userList I updated the table, how to do it better?

        self.tableView.reloadData()
    }  
}

2 个答案:

答案 0 :(得分:1)

您可以使用通知。每当用户列表更新时,都会发布如下通知:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserlistUpdate"), object: nil)

然后,在viewDidLoad中添加:

NotificationCenter.default.addObserver(self, selector: #selector(TableViewController.reloadData), name: NSNotification.Name(rawValue: "UserlistUpdate"), object: nil)

P.S。到目前为止,关于你的架构,我会让TableViewController为Network保存一个变量,而不是拥有自己的用户数组。然后,在AppDelegate中:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let network = Network()

    // Access the TableViewController and set its network variable
    let tableViewController = window!.rootViewController as! TableViewController
    tableViewController.network = network

答案 1 :(得分:1)

正如@JDM在评论中提到的,你的架构很混乱 尝试使用协议执行此委派:

// Network.swift
protocol UsersUpdatedProtocol {
  func usersListUpdated(list: [User])
}
class Network {
  var userList: [User] = [] {
    didSet {
      delegate?.usersListUpdated(list: userList)
    }
  }
  var delegate: UsersUpdatedProtocol?
  init(delegate d: UsersUpdatedProtocol) {
    super.init()
    delegate = d
  }
}

// File TableViewController.swift
class TableViewController: UITableViewController, UsersUpdatedProtocol {
  var userList: [User] = []

  override func viewDidLoad() {
    super.viewDidLoad()
    let _ = Network(delegate: self)
  }
  func usersListUpdated(list: [User]) {
    self.userList = list
    self.tableView.reloadData()
  }
}