2015-07-11 30 views
1

[更新] 我已經添加了實際的代碼片段,以便明確我的問題。Swift數組:如何附加元素引用以便稍後從同步請求中更新元素?

假設我們想將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 

這不存儲圖像的屬性值到目標數組。 雖然圖像OK的塊,如果我通過目標數組迭代,我的形象是零

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 

這不會將圖像屬性值存儲在數組中。

我該怎麼做?

+0

它爲什麼要存儲圖像?你只能插入imageView,你到底想要發生什麼? – luk2302

+0

請嘗試重新說明問題。這很難理解。你的代碼示例也不是很有用。 – idmean

+0

我添加了實際代碼以便於理解 –

回答

0

哎呀!

問題在於Story被定義爲struct。結構與類不同,通過值傳遞。

爲了使代碼正常工作,我剛剛從struct Story {}更改爲class Story {},並且瞧!