【发布时间】:2017-07-13 04:11:24
【问题描述】:
我正在通过 API 获取标签、文本和图像。当 API 有数据时,它显示没有错误。但是当 API 为 nil 时,它会抛出错误:
由于未捕获的异常“NSRangeException”而终止应用程序,原因: '*** -[__NSArray0 objectAtIndex:]: 索引 0 超出范围为空 NSArray'。
如果 API 提供 nil 值但防止崩溃,我需要它显示 null。任何人都请帮助在 Swift 3 中解决这个问题。代码如下:
import UIKit
import Alamofire
class Instructors: UIViewController {
@IBOutlet var fullName: UILabel!
@IBOutlet var post: UILabel!
@IBOutlet var descriptionName: UITextView!
@IBOutlet var instructorImage: UIImageView!
var dictDataContent:NSDictionary = NSDictionary()
var dictData:NSArray = NSArray()
var dictprofile:NSDictionary = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
self.dictData = (dictDataContent.value(forKey: "instructors") as AnyObject) as! NSArray
self.dictprofile = (dictData.object(at: 0) as AnyObject) as! NSDictionary
let url:URL = URL(string: (self.dictprofile.value(forKey: "profile_image")) as! String)!
SDWebImageManager.shared().downloadImage(with: url, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if self != nil {
self?.instructorImage.image = image
}
})
self.fullName.text = dictprofile.value(forKey: "full_name") as! String?
self.post.text = dictprofile.value(forKey: "designation") as! String?
self.descriptionName.text = dictprofile.value(forKey: "description") as! String?
}
}
【问题讨论】:
-
错误消息是它自己的原因,检查数组计数然后从数组中访问对象。您的 'dictDataContent' 没有任何价值或检查键 'instructors'
-
我已经在下面给出了我所有的代码。我检查了 dictDataContent 的条件,它仍然抛出相同的错误,当我检查 dictData 时,它全部返回 nil。我是swift的初学者。请问能详细点吗??请..
-
@Tamannah 为什么不只检查 dictData.count > 0 然后做你在做什么?
-
当我检查dict.count > 0时,它也显示所有给定值的null。
标签: ios swift swift3 alamofire nsrangeexception