gpt4 book ai didi

ios - 迭代对象 Swift - 数组超出索引 - TableView 中的 AlamofireObjectMapper

转载 作者:行者123 更新时间:2023-11-28 08:57:52 25 4
gpt4 key购买 nike

使用 Xcode 7.1

我正在尝试向以下 JSON 发出请求并将其显示在 tableView 中

我正在使用 AlamofireObjectMapper将 JSON 转换为对象。

问题:我不知道如何迭代 tableView 中的对象

下面是自定义类,Alamofire Request & TableView

class WeatherResponse: Mappable {
var location: String?
var threeDayForecast: [Forecast]?

required init?(_ map: Map){}

func mapping(map: Map) {
location <- map["location"]
threeDayForecast <- map["three_day_forecast"]
}
}

class Forecast: Mappable {
var day: String?
var temperature: Int?
var conditions: String?

required init?(_ map: Map){}

func mapping(map: Map) {
day <- map["day"]
temperature <- map["temperature"]
conditions <- map["conditions"]
}
}

Alamofire 请求

//Defined within ViewController
var location: String?
var arrayOfForecasts = [Forecast]()

override func viewDidLoad() {
Alamofire.request(.GET, url).responseObject{(response :WeatherResponse?, error: ErrorType?)in
let location1 = response?.location
self.location = location1

let threeDayForecast1 = response?.threeDayForecast
self.arrayOfForecasts = threeDayForecast1!
print(threeDayForecast1)
self.tableView.reloadData()
} }

当我执行“print(threeDayForecast1)”时,我得到以下输出:[MyAppName.Forecast, MyAppName.Forecast, MyAppName.Forecast]

TableView 协议(protocol)

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
let threeDayObj1 = arrayOfForecasts[indexPath.row]
cell.tempLabel?.text = threeDayObj1.conditions

return cell
}

我得到的错误是:

threeDayObj1 is array out of index

最佳答案

在最新版本的 AlamofireObjectMapper 中,使用 Swift 3、Xcode 8 和 iOS 10,您需要按如下方式执行 get 调用:

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).validate().responseObject { (response: DataResponse< WeatherResponse>) in
...

关于ios - 迭代对象 Swift - 数组超出索引 - TableView 中的 AlamofireObjectMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32583001/

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