2017-06-12 24 views
0

我想只改变一个类的用户列表,称为网络。我不明白如何在userList更改后进行TableView更新。我将在下面的代码中向您展示一个示例和详细问题。如何在某些数据更改后刷新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() 
    } 
} 
+0

你的架构是非常散乱和坏(为什么保持这一个的appdelegate VAR)这是怎么清单得到更新?谁是网络的来电者以检查更新? – JDM

回答

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) 

附:关于你的架构到目前为止,我会让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 
+0

如果不止一件事可以响应用户列表中的更改,则这种方法会很好,因为它们都可以订阅通知。 –

+0

至于架构我可能会建议一个单的方法:公共类'MyClass的{ 静态让sharedInstance = MyClass的() 私有的init(){ } }' –

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() 
    } 
} 
+1

该解决方案将工作,如果只有一件事是怎么回事以响应用户列表的更新。如果不止一件事情会做出反应,那么你可能会更好地使用通知 –

相关问题