ios - 在 Swift 3 中访问闭包外的数组

标签 ios swift multithreading firebase closures

我有这个闭包,我用它来填充我的数组和字典。但是,当我尝试在函数外使用它时,它是空的。我知道这个闭包在异步线程上工作,所以假设我在它被填充之前尝试访问该变量是否正确?结果,我得到一个空数组。这是我的代码。

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.
}

处理这种多线程执行的最佳方法是什么?

最佳答案

我遵循 Raywenderlich 及其团队的编码标准(针对 Swift)。如果我要重写你的代码来拥有强大的 self ,那就是这样的:

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 self] (snapshot) in

                guard let strongSelf = self else {
                    return
                }

                let enumerator = snapshot.children
                while let entry = enumerator.nextObject() as? FIRDataSnapshot {
                    strongSelf.entryIDS.append(entry.key)
                    strongSelf.entries[entry.key] = DiaryEntry(snapshot: entry)
                }
                strongSelf.entryIDS.reverse()
                strongSelf.collectionView?.reloadData()
            })
            print("Entries: \(entryIDS.count) ")
        }
        // Do any additional setup after loading the view.
}

我希望这能奏效。在连接到任何 API(例如 Firebase 和 Alamofire)时,我也是这样编写代码的。

关于ios - 在 Swift 3 中访问闭包外的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42015954/

相关文章:

ios - 为什么整个单词的 sizeWithFont 不同于其字母大小的总和?

swift - 如何处理两个 TableView 关联?

c++ - QThread::quit() 是立即结束线程还是等到返回事件循环?

.net - 等待异步模式和工作窃取线程

ios - 如何限制 UITextfield 中的空格?

ios - 如何将当前位置设置为 request.source Swift 3

ios - 除非用户先在 map 上移动,否则 Mapbox iOS 的 flyToCamera 会一直回到初始位置

swift - 如何在 Swift 中过滤 NSArray?

swift - RxSwift BehaviourRelay 取消之前的调用,仅使用最近的调用

c++ - 使用 PBO 上传 OpenGL 纹理?