2016-07-07 7 views
0

新しいParse(parse.com)です。私はparse.comのような種類のテーブルを持っています: enter image description hereswift: "Parse"から画像を取得する

そして私はこれらの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)") 
      } 
     } 
    } 
} 

ここに私のコードはありますが、すべての点で問題ありません。しかし、私はエラーがあります:範囲外のインデックス。私のリーグ映像配列は空です。ありがとうございました。

答えて

0

あなたの問題はleaguesleaguesImagesが同期しなくなっていることです。 Parseから配列を取得するとすぐにleaguesを追加しますが、leaguesImagesgetDataInBackgroundWithBlockが完了した後に追加されます。

イメージデータをすぐにダウンロードして別の配列に保存する代わりに、カスタムセルにleaguesプロパティを追加してそこにデータをダウンロードしてイメージを適用します。

leaguesImages配列に値を設定しているような配列を挿入することは、どちらが最初にダウンロードを終了するのかわからないため、順序が重要な場合は悪い考えです。おそらく2番目のリーグのイメージが最小です最初のリーグのイメージとして。 (PS:画像のサイズだけでダウンロードの時間が決まります)

+0

あなたの答えはありがたいですが、私はこの文章で何を意味するのか分かりません。「あなたのカスタムセルにリーグのプロパティを追加しますそこにデータをダウンロードしてイメージを適用する」と語った。 –

+0

'var league:PFObject'プロパティをセルに追加し、そのプロパティの' didSet'でデータを取得します。 – EmilioPelaez

+0

whatsはセルにプロパティを追加する意味ですか? Plsは、完全に答えることができます。モバイル開発の新機能 –

関連する問題