2016-04-15 55 views
2

這是我使用MVC設計模式的第一個程序,我堅持如何從模型中獲取值並將其顯示在我的視圖中。我會告訴你我做了什麼。請澄清我做錯了什麼?或者告訴我如何以其他方式完成。如何從模型中獲取值到控制器

型號

class songData: NSObject { 

var artistName: String 
var albumName: String 

init(artistName: String, albumName: String) { 
    self.artistName = artistName 
    self.albumName = albumName 
} 

} 

控制器

@IBAction func doTheSearch(sender: AnyObject) { 

    itunesAPI().itunesSearch({(song : songData) in 


    }) 

    self.tableView.reloadData() 

} 

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

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

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

     var artistAndAlbum = itunesAPI().array[indexPath.row] 

    cell.textLabel?.text = 
    cell.detailTextLabel?.text = 

    return cell 

} 

API

func itunesSearch(completionHandler:(songData)->()) { 

    Alamofire.request(.GET, "http://itunes.apple.com/search?", parameters: ["term" : "tamil new songs", "media" : "music"]) 

     .responseJSON { (response) in 

      let json = JSON(response.result.value!) 



      if let jsonData = json["results"].arrayObject { 
       self.array = jsonData as! [[String : AnyObject]] 


      if self.array.count > 0 { 
//     self.array = jsonData as! [[String : AnyObject]] 
//     if let resultsDict = resultsArray.first { 


       let albumName = json["results"]["collectionName"].stringValue 
       let artistName = json["results"]["artistName"].stringValue 


       let song = songData(artistName: artistName, albumName: albumName) 

       completionHandler(song) 


     } 

     } 

我有我的看法E中的什麼除了由單個單元格組成的表格視圖組成的故事板。我需要從API獲取響應並在視圖中顯示它。

回答

0

首先,您將要在數據返回後重新加載表格。將你的IBAction更新爲:

itunesAPI().itunesSearch({(song : songData) in 
    self.tableView.reloadData() 
}) 

否則在數據返回之前reloadData會被調用。在viewController上設置一個屬性來保存數據。另外,最好用大寫字母開始一個類名。

var tableData:[SongData] = [SongData]() 

然後設置此變量當數據成功返回:

itunesAPI().itunesSearch({(song : songData) in 
    self.tableData.append(song) // add the result to the list of data 
    self.tableView.reloadData() // reload the table 
}) 

然後設置細胞作爲這樣:

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

    var artistAndAlbum = self.tableData[indexPath.row] 

    cell.textLabel?.text = artistAndAlbum.artistName 
    cell.detailTextLabel?.text = artistAndAlbum.albumName 

    return cell 

} 
+0

真棒人!!但沒有顯示在我的表格視圖?! –

+0

通過json值對下標進行一些改變,我得到了結果。感謝您的幫助夥計! –

相關問題