gpt4 book ai didi

ios - 使用 ObjectMapper - 如何将 JSON 结果快速转换为 TableView

转载 作者:行者123 更新时间:2023-11-30 13:23:21 24 4
gpt4 key购买 nike

我在将 JSON 结果传递到用于在 TableView 中显示的数组时遇到问题。

这是我的模型:

class Restaurant: Mappable {

var lat: Float?
var lng: Float?
var address: String?
var name: String?

required init?(_ map: Map) { }

// Mappable
func mapping(map: Map) {
lat <- map["venue.location.lat"]
lng <- map["venue.location.lng"]
address <- map["venue.location.address"]
name <- map["venue.name"]
}
}

这是我的 ViewController

class ListViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var listRestaurants: [Restaurant] = []

override func viewDidLoad() {
super.viewDidLoad()
retrieveFoursquareList()
tableView.reloadData()
}

func retrieveFoursquareList(){
let foursquareService = FoursquareService()

foursquareService.getFoursquare {
(let response) in

if let currrently = response {
dispatch_async(dispatch_get_main_queue()) {
print("RESULTADO 2 array: \(currrently)")

for restaurant in currrently {
if let name = restaurant.name {
restaurant.name = name
print("RESULTADO 3 row: \(restaurant.name)")
self.listRestaurants.append(restaurant)
print("RESULTADO 4 array: \(self.listRestaurants)")

}

}
}
}
}
}
}

extension ListViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listRestaurants.count
}

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

let cell = tableView.dequeueReusableCellWithIdentifier("RestautantsCell", forIndexPath: indexPath) as! RestaurantCell


let listRestaurant = listRestaurants[indexPath.row]

cell.nameLabel.text = listRestaurant.name
cell.addressLabel.text = listRestaurant.address
return cell
}

}

在图像中,您可以看到我的 JSON 结果正常。我的问题是如何将此结果传递到 de var listRestaurant 数组中:

JSON output is OK but I have problem passing this JSON into the var listRestaurant array

我将感谢您的帮助。谢谢。

最佳答案

您似乎没有设置 tableview 委托(delegate),

在 viewDidLoad 中,添加以下代码:

tableView.dataSource = self
tableView.delegate = self

这段代码:

for restaurant in currrently {
if let name = restaurant.name {
restaurant.name = name

您还将餐厅名称设置为餐厅名称,我认为此行没有任何好处,如果您只想在添加之前检查名称是否已设置,请执行以下操作:

if let _ = restaurant.name {
self.listRestaurants.append(restaurant)
}

你使用的映射,我不熟悉,所以我不确定这个,但是文档here (如果这是您正在使用的)建议您创建一个如下所示的对象:

let restaurant = Mapper<Restaurant>().map(restaurantData)

我不确定你是否可以按照你现在的方式来转换它,但是,我不确定。

tableView不显示的主要原因是没有设置委托(delegate)函数。

关于ios - 使用 ObjectMapper - 如何将 JSON 结果快速转换为 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com