【发布时间】:2017-02-03 02:50:38
【问题描述】:
我有这个闭包,我用它来填充我的数组和字典。但是,当我尝试在函数之外使用它时,它是空的。我知道这个闭包在异步线程上工作,所以假设我在填充之前尝试访问该变量是否正确?结果,我得到一个空数组。这是我的代码。
class HomeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIGestureRecognizerDelegate {
var entries = [String: DiaryEntry]()
var entryIDS = [String]()
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(DiaryCell.self, forCellWithReuseIdentifier: "homeCell")
collectionView?.backgroundColor = UIColor.white
navigationController?.hidesBarsOnSwipe = true
if let userID = FIRAuth.auth()?.currentUser?.uid {
FirebaseService.service.getUserEntriesRef(uid: userID).observe(.value, with: { [weak weakSelf = self] (snapshot) in
let enumerator = snapshot.children
while let entry = enumerator.nextObject() as? FIRDataSnapshot {
weakSelf?.entryIDS.append(entry.key)
weakSelf?.entries[entry.key] = DiaryEntry(snapshot: entry)
}
weakSelf?.entryIDS.reverse()
weakSelf?.collectionView?.reloadData()
})
print("Entries: \(entryIDS.count) ")
}
// Do any additional setup after loading the view.
}
处理这种多线程执行的最佳方法是什么?
【问题讨论】:
标签: ios swift multithreading firebase closures