2015-06-09 3 views
0

Я получаю изображения от запроса async и добавляю их в [UIImage](), чтобы я мог заполнить мои изображения UITableView теми, что из массива. Проблема в том, что я продолжаю получать Fatal error: Array index out of range в функции cellForRowAtIndexPath, когда это вызвано, и я подозреваю, что это может быть потому, что я делаю асинхронный вызов? Почему я не могу добавить изображение из массива в строку таблицы?Swift: отображать изображение из массива UIImage в виде таблицы

var recommendedImages = [UIImage]() 

     var jsonLoaded:Bool = false { 
      didSet { 
       if jsonLoaded { 

        // Reload tableView on main thread 
        dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1 
         dispatch_async(dispatch_get_main_queue()) { // 2 
          self.tableView.reloadData() // 3 
         } 
        } 

       } 
      } 
     } 

    override func viewDidLoad() { 
      super.viewDidLoad() 

      // ... 

      let imageURL = NSURL(string: "\(thumbnail)") 

      let imageURLRequest = NSURLRequest(URL: imageURL!) 

      NSURLConnection.sendAsynchronousRequest(imageURLRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, error in 

      if error != nil { 

       println("There was an error") 

     } else { 

       let image = UIImage(data: data) 

       self.recommendedImages.append(image!) 

       self.jsonLoaded = true 

     } 

     }) 

    } 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     var songCell = tableView.dequeueReusableCellWithIdentifier("songCell", forIndexPath: indexPath) as! RecommendationCell 

     songCell.recommendationThumbnail.image = recommendedImages[indexPath.row] 


     return songCell 
    } 

Edit: Мой numberOfRowsInSection метод. recommendedTitles - это тот же блок кода, который я исключил. Это всегда будет 6.

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

Можете ли вы опубликовать метод 'numberOfRowsInSection'? – Leo

ответ

1

Ваша ошибка вы вернетесь 6 в numberOfRowsInSection, так TableView знаю, что у вас есть 6 клеток

Но, когда выполнить cellForRowAtIndexPath, ваш массив изображений пуст, поэтому он разбился ,

Попробуйте

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

Также перейти на главную очередь, это достаточно

dispatch_async(dispatch_get_main_queue(), {() -> Void in 
     self.tableView.reloadData() 
    }) 
Смежные вопросы