gpt4 book ai didi

ios - 如何在 Swift 中的转义 block 内正确访问 self

转载 作者:行者123 更新时间:2023-11-30 11:45:50 25 4
gpt4 key购买 nike

我在下面的代码中遇到了一些崩溃。我认为崩溃是由 block (LoadXZYAPI)转义和已释放的 ViewControllerA 的访问属性引起的。因此,当访问strongSelf.data.*时,strongSelf返回nil或在dealloc内存位置并导致崩溃。

有什么方法可以防止这种崩溃,而无需在每次尝试访问其属性(data.*)时检查strongSelf?在这种情况下,在不使 LoadXZYAPI 不转义的情况下,最佳实践是什么?

提前致谢

class ViewControllerA {

var data: [String: Any]?

func loadData(){

LoadXZYAPI() { [weak self] (data:Any?) in

if let strongSelf = self {

strongSelf.data = data

DispatchQueue.global(qos:.default).asyc {

// process self.data
let imageData = GetImageData(data:strongSelf.data["image_name"])

if let data = data, let image = UIImage(data:imageData) {

DispatchQueue.main.async {
strongSelf.imageView = nil

strongSelf.imageView = CustomView(image: image) <-- Crashes randomly after this line
strongSelf.imageView!.width = strongSelf.map["width"] as? CGFloat
strongSelf.imageView!.height = strongSelf.map["height"] as? CGFloat
strongSelf.imageView!.backgroundColor = UIColor.init(hex: "#efefef")
strongSelf.imageViewWrapper.addSubview((strongSelf.imageView)!)
strongSelf.imageViewWrapper.bringSubview(toFront: (strongSelf.imageView)!)
strongSelf.imageView!.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
(strongSelf.imageView?.leadingAnchor)!.constraint(equalTo: (strongSelf.imageViewWrapper?.leadingAnchor)!),
(strongSelf.imageView?.trailingAnchor)!.constraint(equalTo: (strongSelf.imageViewWrapper?.trailingAnchor)!),
(strongSelf.imageView?.topAnchor)!.constraint(equalTo: (strongSelf.navigationController?.navigationBar.bottomAnchor)!),
(strongSelf.imageView?.bottomAnchor)!.constraint(equalTo: (strongSelf.imageViewWrapper?.bottomAnchor)!),
])

self?.didUpdateImageView()
}
}
}
}
}
}
}

最佳答案

这应该是安全的:

func loadData(){

LoadXZYAPI() { [weak self] (data:Any?) in

//didn't bother putting a guard here since you don't need a strong ref here
self?.data = data

DispatchQueue.global(qos:.default).asyc {

guard let strongSelf1 = self else {
return
}

//use strongSelf1

DispatchQueue.main.async {

guard let strongSelf2 = self else {
return
}

//use strongSelf2
}
}
}
}

关于ios - 如何在 Swift 中的转义 block 内正确访问 self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48836672/

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