swift – viewDidLoad中之前和之后的区别

前端之家收集整理的这篇文章主要介绍了swift – viewDidLoad中之前和之后的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将searchBar设置为viewDidLoad中的tableHeaderView:
override func viewDidLoad() {
    super.viewDidLoad()


    // SearchController initializiation
    self.searchController = UISearchController.init(searchResultsController: nil)
    self.searchController.delegate = self
    self.searchController.searchBar.delegate = self
    self.searchController.searchBar.sizeToFit()
    self.searchController.searchResultsUpdater = self
    self.searchController.searchBar.barTintColor = UIColor.white
    self.searchController.searchBar.keyboardAppearance = .default
    self.searchController.searchBar.backgroundColor = UIColor.white
    self.searchController.hidesNavigationBarDuringPresentation = true
    self.searchController.obscuresBackgroundDuringPresentation = false


    self.tableView.tableHeaderView = self.searchController.searchBar
    self.definesPresentationContext = true

    self.fetch()
    self.tableView.reloadData()

}

这个我的fetch()函数

func fetch() {
    let fetchRequest:NSFetchRequest<Phone> = Phone.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "header",ascending: true),NSSortDescriptor.init(key: "date",ascending: true)]

    self.fetchedResultsController = NSFetchedResultsController.init(fetchRequest: fetchRequest,managedObjectContext: self.managedObjectContext,sectionNameKeyPath: "header",cacheName: nil)
    self.fetchedResultsController.delegate = self

    do {
        try self.fetchedResultsController.performFetch()
        self.tableView.reloadData()
    } catch {}

}

但我不明白他们是不会工作的. Xcode崩溃,实际上没有发生.然后我尝试改变viewDidLoad里面的内容

override func viewDidLoad() {
    super.viewDidLoad()

    self.fetch()
    self.tableView.reloadData()

    // SearchController initializiation
    self.searchController = UISearchController.init(searchResultsController: nil)
    self.searchController.delegate = self
    self.searchController.searchBar.delegate = self
    self.searchController.searchBar.sizeToFit()
    self.searchController.searchResultsUpdater = self
    self.searchController.searchBar.barTintColor = UIColor.white
    self.searchController.searchBar.keyboardAppearance = .default
    self.searchController.searchBar.backgroundColor = UIColor.white
    self.searchController.hidesNavigationBarDuringPresentation = true
    self.searchController.obscuresBackgroundDuringPresentation = false


    self.tableView.tableHeaderView = self.searchController.searchBar
    self.definesPresentationContext = true



}

成功!工作正常我不明白有什么区别?

这是因为您设置了searchResultsUpdater和searchBar的代理,甚至在您的fetchedResultsController被初始化之前.你的代码searchResultsUpdater或searchBar的代理方法中的某些地方访问你的fetchedResultsController并且得到它,所以你的应用程序崩溃.我的建议是避免崩溃是使searchResultsController作为计算或惰性属性.
原文链接:https://www.f2er.com/swift/319549.html

猜你在找的Swift相关文章