gpt4 book ai didi

ios - 向下滚动时出现 fatal error

转载 作者:行者123 更新时间:2023-11-28 15:21:17 25 4
gpt4 key购买 nike

我在 tableView 中传递 json,但当我向下滚动几次时它显示消息“ fatal error :在展开可选值时意外发现 nil”

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView: UIImageView {

var imageUrlString: String?

func loadImageUsingUrlString(_ urlString: String) {

imageUrlString = urlString

let urlEncoded = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)

let url = URL(string: urlEncoded!)

image = nil

if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}


// crush here down line
URLSession.shared.dataTask(with: url!, completionHandler: {(myData, respones, error) in

if error != nil {
print(error ?? 0)
return
}

DispatchQueue.main.async(execute: {

let imageToCache = UIImage(data: myData!)

if self.imageUrlString == urlString {
self.image = imageToCache
}

imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
})

}).resume()
}

}

enter image description here

最佳答案

将您的 URLSession.shared.dataTask(with:completionHandler:) 包含在 if-let 子句中,如下所示:

if let url = url {
URLSession.shared.dataTask(with: url, completionHandler: {(myData, respones, error) in

if error != nil {
print(error ?? 0)
return
}

DispatchQueue.main.async(execute: {

let imageToCache = UIImage(data: myData!)

if self.imageUrlString == urlString {
self.image = imageToCache
}

imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
})

}).resume()
}

注意并且尽量不要使用force-unwrapping (!)。尽可能使用 optional bindingif-let


编辑

因为您可能是 optional 的新手,所以我发布了可能的崩溃处理代码。虽然我没有改变逻辑,但我修复了可能与崩溃相关的代码:

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView: UIImageView {

var imageUrlString: String?

func loadImageUsingUrlString(_ urlString: String) {

imageUrlString = urlString

guard let urlEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
print("Encoding not done")
return
}

let url = URL(string: urlEncoded)

image = nil

if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}


if let url = url {
URLSession.shared.dataTask(with: url, completionHandler: {(myData, respones, error) in

if error != nil {
print(error ?? 0)
return
}

if let myData = myData {
DispatchQueue.main.async(execute: {

let imageToCache = UIImage(data: myData)

if self.imageUrlString == urlString {
self.image = imageToCache
}

if let imageToCache = imageToCache {
imageCache.setObject(imageToCache, forKey: urlString as AnyObject)
}
})
}

}).resume()
}
}

}

关于ios - 向下滚动时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45953107/

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