[2] KVO

作者: coderzcj | 来源:发表于2017-12-08 10:37 被阅读13次
    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

          本文链接:https://www.haomeiwen.com/subject/zcteixtx.html