[2] KVO

import UIKit

class NewsAPI: NSObject {
    
    static let service = NewsAPI()
    
    @objc dynamic private(set) var articles: [String] = []

    func fetchArticles(for source: String) {
        
    }
    
    func resetArticles() {
    }
    
}

class ArticleListController: UITableViewController {
    
    var source: String?
    
    private var token: NSKeyValueObservation?
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        guard let source = source else { return }
        
        /*
         let path1 = #keyPath(NewsAPI.articles)
         let path2 = \NewsAPI.articles
         let path3 = \.articles
         */
        token = NewsAPI.service.observe(\.articles) {
            _, _ in
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        NewsAPI.service.fetchArticles(for: source)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        token?.invalidate()
        NewsAPI.service.resetArticles()
    }
    
}

你可能感兴趣的:([2] KVO)