2016-07-07 84 views
0

解析(parse.com)中的新问题。我有parse.com这样的表: enter image description hereswift:从“解析”中检索图像

而我想检索这3个图像,并把它放在表视图行。这里是我的代码:

class LeaguesTableViewController: UITableViewController { 

    var leagues = [PFObject]() { 
     didSet { 
      tableView.reloadData() 
     } 
    } 

    var leaguesImage = [NSData]() { 
     didSet { 
      tableView.reloadData() 
     } 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     loadData() 
     tableView.registerClass(LeaguesTableViewCell.self, forCellReuseIdentifier: "ReusableCell") 
    } 

    // MARK: - Table view data source 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

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

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return 160 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("ReusableCell", forIndexPath: indexPath) as! LeaguesTableViewCell 

     cell.leagueImage.image = UIImage(data: leaguesImage[indexPath.row]) 
     cell.leagueNameLabel.text = leagues[indexPath.row]["name"] as? String 

     return cell 
     } 

    // MARK: Parse 

    func loadData() { 

     let query = PFQuery(className: "Leagues") 
     query.findObjectsInBackgroundWithBlock { (objects, error) in 
      if(objects != nil && error == nil) { 

       // List of leagues 
       for i in objects! { 
        self.leagues.append(i) 

        // Retrieve images 
        let imageFile = i["image"] as? PFFile 
        imageFile!.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in 
         if error == nil { 
          if let imageData = imageData { 
           self.leaguesImage.append(imageData) 

          } 
         } 
        } 
       } 

      } else if error != nil { 
       print("Error is: \(error)") 
      } 
     } 
    } 
} 

这里是我的代码,并从我的观点是一切正常。但我有错误:索引超出范围。我的leaguesImages数组是空的。谢谢。

回答

0

您的问题是leaguesleaguesImages不同步。一旦您从Parse中检索数组,您将立即添加leagues,但仅在getDataInBackgroundWithBlock完成后才添加leaguesImages

不是立即下载图像数据并将其存储在单独的阵列中,而是将leagues属性添加到您的自定义单元格中,然后在那里下载数据并应用图像。

填充像你这样的数组填充leaguesImages数组是一个坏主意,当顺序很重要,因为你不知道哪一个会先完成下载,也许第二个联赛图像是最小的,并且它将被设置作为第一个联赛的形象。 (PS:图像大小不是唯一指示下载需要多长时间的东西)

+0

感谢您的回答,但我不明白您在这句话中的含义:“我会将联赛属性添加到您的自定义单元格中,并在那里下载数据并应用图像。“ –

+0

向您的单元格添加'var league:PFObject'属性,并获取该属性的'didSet'中的数据。 – EmilioPelaez

+0

什么意思是将属性添加到单元格?请问,你能完全回答吗?移动开发新手 –