如何使用模型类从数组中获取数据

时间:2017-09-22 12:04:07

标签: json iphone model-view-controller ios10

我没有使用模型类从数组中获取数据,但数组中包含数据。我不知道使用模型类的正确方法。也许我实施的方式是错误的。请指导。

代码:

// . ViewController class

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // let cell: VisitorsCell = tableView.dequeueReusableCell(withIdentifier: "VisitorsCell", for: indexPath) as! VisitorsCell

    let cell:RecentVisitorsCell = self.tblView.dequeueReusableCell(withIdentifier: "VisitorsCell") as! VisitorsCell

    **let ds:VisitorDs = recentVisitorsArray[indexPath.row] as! VisitorsDs // . crash here.//**

   // let ds = VisitorsDs()

    cell.imgProfile.image = UIImage(named: ds.profile)
    cell.lblAge.text = ds.age as String

    return cell

}
//MARK: Delegatres Server Communication
func didFinishServerCommunicationWithSuccess(_ response:ServerResponse){
    print("api response: ", response.infoResponse?["data"] as! [AnyObject])

    //VisitorsArray = response.infoResponse?["data"] as! [AnyObject] as NSArray

    //if response.operation == "SERVICE_SOURCE" {
        if let dictResult = response.infoResponse as? NSDictionary {
           if let arrResult = dictResult.object(forKey: "data") as? NSArray
           {
            for result in arrResult {
                let Visitors = VisitorsDs()

                recentVisitors.initWithVal(dict: result as! NSDictionary)
                VisitorsArray.add(VisitorsDs.self)
            }
            print("array received: ", VisitorsArray)
            self.tblView.reloadData()
        }
    }

    self.tblView.reloadData()

}

// Model class

 class VisitorsDs:NSObject  {


var profile:String = ""
var name:String = ""

/*
//MARK: Initialization
init(profile:String,name:String,age:String,parentsName:String,mobile:String,purpose:String,date:String,time:String,clinic:String ) {

self.profile = profile
self.name = name
}
*/

func initWithVal(dict: NSDictionary) {
   // print(dict)

    if let latestValue = dict["image_path"] as? String {
        self.profile = latestValue
    }
    if let latestValue = dict["first_name"] as? String {
        self.name = latestValue
    }
  }
}
  

错误:无法将“IPAN.VisitorsDs”(0x10d809f58)类型的值转换为“IPAN.VisitorsDs”(0x10d806eb0)。

请指导,uitableview中的值为空,但数组中存在值。

1 个答案:

答案 0 :(得分:0)

我建议使用新的Swift 4 Codable协议将JSON解析为模型,然后在tableview中使用起来会更容易。一个教程:

https://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375

BTW你的回答是什么?