【问题标题】:Iterating Over Objects Swift - Array out of Index - AlamofireObjectMapper in TableView迭代对象 Swift - 数组超出索引 - TableView 中的 AlamofireObjectMapper
【发布时间】:2015-12-11 12:41:53
【问题描述】:

使用 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 协议

 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

【问题讨论】:

  • 哪里出错了? threeDayObj1 是threeDay?
  • 对不起,问题中有一个错字。我已经更正了。错误在threeDayObj1 = arrayOfForecasts [indexPath.row]

标签: ios swift uitableview alamofire


【解决方案1】:

在最新版本的 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
...

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多