【问题标题】:indexout of range error while getting image array获取图像数组时出现索引超出范围错误
【发布时间】:2019-06-17 18:27:11
【问题描述】:

您好,我正在从响应中获取图像数组,但我正在获取整个数组,但有时我得到 1 个图像,有时是 5 个图像,所以当我填充图像视图时,我得到索引超出范围错误让我告诉你响应

模型类

struct PreviousInspListModel {
    var resolved: String
    var type: String
    var notes: String
    var property_id: String
    var regulation_item: String
    var locations: String
    var id: String
    var boiler_service_date: String
    var action: String
    var intervention_required: String
    var regulation_id: String
    var regulation_item_name: String
    var contravention: String
    var contraventions_item_name: String
    var imagesArray : [String]!
}

回应

[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"]))]



[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"])), RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "dsds", property_id: "22", regulation_item: "8", locations: "asdsad", id: "65", boiler_service_date: "", action: "Maintenance Attention Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5aQueNfpUp1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_8dlP5RlUqS1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_fqqqC9zfe91548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_sjkjOy73Y11548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_t7ePWkHif71548247477.png"]))]

当我向您展示第一个响应时,我只得到一个图像,第二个我得到 5 个图像,现在我将向您展示我的代码

代码

var preInspData = [PreviousInspListModel]()

func previousInspAPI(){
    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"

    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!, "access_token": A_Token!,"property_id": propertyID!]
    print(params)
    SVProgressHUD.show()
    Alamofire.request(previousinspectionslist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let data = json["data"]

            data.array?.forEach({ (iList) in
                let i_List = PreviousInspListModel(resolved: iList["resolved"].stringValue, type: iList["type"].stringValue, notes: iList["notes"].stringValue, property_id: iList["property_id"].stringValue, regulation_item: iList["regulation_item"].stringValue, locations: iList["locations"].stringValue, id: iList["id"].stringValue, boiler_service_date: iList["boiler_service_date"].stringValue, action: iList["action"].stringValue, intervention_required: iList["intervention_required"].stringValue, regulation_id: iList["regulation_id"].stringValue, regulation_item_name: iList["regulation_item_name"].stringValue, contravention: iList["contravention"].stringValue, contraventions_item_name: iList["contraventions_item_name"].stringValue, imagesArray: iList["images"].arrayObject as? [String])
                self.preInspData.append(i_List)
                print(self.preInspData)
            })
            self.tblListView.reloadData()
            SVProgressHUD.dismiss()
        case.failure(let error):
            print(error.localizedDescription)
        }

    })
}

   func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return preInspData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PreviousInspectionsTableViewCell
        cell.lblItem.text = preInspData[indexPath.row].regulation_item_name
        cell.lblContrevation.text = preInspData[indexPath.row].contraventions_item_name
        cell.lblLocation.text = preInspData[indexPath.row].locations
        cell.lblAction.text = preInspData[indexPath.row].action
        cell.lblNotes.text = preInspData[indexPath.row].notes
        cell.lblStatus.text = preInspData[indexPath.row].intervention_required

        let images = preInspData[indexPath.row].imagesArray

        let image1 = images![0]
        if image1 != ""{
            let imageUrl = URL(string: image1)!
            cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image2 = images![1]
        if image2 != ""{
            let imageUrl = URL(string: image2)!
            cell.img2.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image3 = images![2]
        if image3 != ""{
            let imageUrl = URL(string: image3)!
            cell.img3.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image4 = images![3]
        if image4 != ""{
            let imageUrl = URL(string: image4)!
            cell.img4.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image5 = images![4]
        if image5 != ""{
            let imageUrl = URL(string: image5)!
            cell.img5.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        cell.selectionStyle = .none
        return cell
    }

所以现在如果数组中只有一个图像那么我会得到索引超出范围错误所以如何处理这个请帮助我

【问题讨论】:

  • 究竟是哪一行代码导致了错误?
  • 意味着如果我在数组中获得 5 张图像,那么我不会收到错误,但如果我只获得一张图像,我会在 let image2 = images![1] if image2 != ""{ let imageUrl = URL(string: image2)! cell.img2.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil) } 收到错误
  • 代码行let images = preInspData[indexPath.row].imagesArray处的preInspData是什么?
  • 我的模型类数组等待我将用模型类更新问题
  • 如果不能保证数组中有那么多元素,请不要编写假定数组中有特定数量元素的代码。

标签: ios arrays swift alamofire


【解决方案1】:

问题在于从索引不存在的数组中获取元素。即索引超出范围

您的行代码单元格导致问题:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}

此问题的解决方案是通过添加此扩展方法来处理索引超出范围错误:

 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}

用法:

if let image1 = images[safe: 0], image1 != "" {
        let imageUrl = URL(string: image1)!
        cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}

【讨论】:

  • @vishal 然后您将获得一个 nil 值,这样您就可以处理索引超出范围错误。我认为这将帮助您解决问题。
猜你喜欢
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
相关资源
最近更新 更多