【发布时间】:2017-05-11 06:26:12
【问题描述】:
我创建了一个带有自定义单元格的 tableView,每个单元格都有一个图像。
在模型类中,我创建了一个func mainPulatesData(),使用URLSession dataTask方法从url中检索数据,并在完成处理程序块中将数据转换为UIImage,然后将图像添加到@数组的变量中987654324@。
检索数据并将它们添加到UIImage 数组的过程在DispatchQueue.global(qos: .userInitiated).async 块中执行。根据打印消息,图像确实被添加到数组中。
然而,即使我在tableView控制器中创建了一个模型类的实例,并在viewDidlLoad中调用mainPulatesData(),图像也没有出现在表格中。
根据表格视图控制器类中的其他打印消息,我发现它甚至可以添加到模型类中的数组中,但似乎不适用于 tableView 控制器中的模型类实例。
这是模型类中获取图像数据的代码:
func mainPulatesData() {
let session = URLSession.shared
if myURLs.count > 0{
print("\(myURLs.count) urls")
for url in myURLs{
let task = session.dataTask(with: url, completionHandler: { (data,response, error) in
let imageData = data
DispatchQueue.global(qos: .userInitiated).async {
if imageData != nil{
if let image = UIImage(data: imageData!){
self.imageList.append(image)
print("\(self.imageList.count) images added.")
}
}
else{
print("nil")
}
}
})
task.resume()
}
}
}
这是视图控制器中创建模型实例的代码:
override func viewDidLoad() {
super.viewDidLoad()
myModel.mainPulatesURLs()
myModel.mainPulatesData()
loadImages()
}
private func loadImages(){
if myModel.imageList.count > 0{
tableView.reloadData()
}
else{
print("data nil")
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myModel.imageList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell
if myModel.imageList.count > 0{
let image = myModel.imageList[indexPath.row]
cell.tableImage = image
return cell
}
return cell
}
【问题讨论】:
-
是延迟加载的概念。为此,您可以使用 SDWebImage(第三方库)
标签: swift uitableview nsurlsessiondatatask