[更新] 我添加了实际的代码片段以使我的问题更清楚。
假设我们想将 uiimages 存储到一个数组中,这些数组是从互联网上获取的。
我有这段代码:
// Somewhere in a loop
{
var story = Story()
story.imgUrl = "http:\(imgUrl)"
/// Donwload image, and replace in the top
if let imgUrl = story.imgUrl {
if let url = NSURL(string: imgUrl) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) -> Void in
if let data = data {
story.image = UIImage(data: data)
var i = 0
for a in self.Stories {
print("iv image \(i++) is \(a.image)")
}
print("Received image for story as \(story.image) into story \(story)")
// Should one set the image view?
if let _ = self.imageView {
if let indexPath = self.tableView?.indexPathForSelectedRow {
if stories.count == indexPath.section { // is that the currently selected section?
self.imageView?.image = story.image
self.imageView?.hidden = false
print("Set imageView withstory \(story.tag.string)")
}
}
}
}
}
}
}
stories.append(story)
}
/// Switch data source
self.Stories = stories
这不会将图像属性值存储到目标数组中。 虽然图像在 block 中没问题,但如果我遍历目标数组,我的图像为零
image: Optional(<UIImage: 0x7ff14b6e4b20> size {100, 67} orientation 0 scale 1.000000))
iv image 0 is nil
如何实现以上功能?
[初始问题]
假设我们要存储元素,即我从互联网上获取的 UIImages。我有这个代码片段:
var array = []
let imageView = UIImageView(image:nil)
array.append(imageView)
// and later or, in an synch block
imageView.image = image
这不会将图像属性值存储在数组中。
我该怎么做?
最佳答案
明白了!
重点是 Story 被定义为结构体。与类不同,结构通过值传递。
为了让代码正常工作,我刚刚从 struct Story {} 更改为 class Story {},瞧!
关于ios - swift 数组 : how to append element references in order to update element later on from a synch request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355346/