gpt4 book ai didi

arrays - 无法将数据输入到类模型(swift)

转载 作者:可可西里 更新时间:2023-11-01 02:18:03 25 4
gpt4 key购买 nike

我正在尝试从其默认类中获取图像以存储在我自己的类模型中。图像似乎加载正常,但它没有存储到我的类(class)。这是我的代码

数据图像模型

 class dataImage {
var userId: String
var value: Double

var photo: UIImage?

init(userId:String, value: Double, photo: UIImage?){
self.userId = userId
self.value = value
self.photo = photo
}

View Controller

    for asset in photos{
asset.fetchFullScreenImageWithCompleteBlock({ image, info in
let images = image
let data1 = dataImage(userId: "1", value: 1.0, photo: images)
self.datas += [data1]
print("*")
})
}
print("datas: \(datas.count)")

所以我在照片中有 6 个“图像”并且“*”打印了 6 次,但是 datas.count 为 0,如何解决这个问题?

最佳答案

asset.fetchFullScreenImageWithCompleteBlock 调用是异步的并立即返回。因此,您的 for 循环完成得非常快,而所有 6 次 Assets 提取都在后台进行。到 print 执行时,提取尚未完成,因此每个提取的完成 block 尚未运行。

克服这个问题的一个简单方法是将 print 放在完成 block 中,并用一个 if 包围,它可以计算照片的数量。类似的东西:

let completed = 0
for asset in photos{
asset.fetchFullScreenImageWithCompleteBlock({ image, info in
let images = image
let data1 = dataImage(userId: "1", value: 1.0, photo: images)
self.datas += [data1]
print("*")
tableView.reloadData()
completed++
if completed == photos.count {
print("datas: \(datas.count)")
}
})
}

由于您希望最终在 tableView 中显示它,因此我在适当的位置包含了 reloadData

然后

func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
return datas.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var data = datas[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier... etc
}

关于arrays - 无法将数据输入到类模型(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34890905/

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