gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:15:10 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com