由于未捕获的异常"NSRangeException"而终止应用,原因:"*** -[__NSArray0对象索引:]:索引 0 超出空 NSArray 的边界"



>我正在通过API获取标签,文本和图像。当 API 有数据时,它显示没有错误。但是当 API 为 nil 时,它会抛出错误:

由于未捕获的异常"NSRangeException"而终止应用程序,原因: '*** -[__NSArray0 objectAtIndex:]:索引 0 超出空的边界 国安局'。

如果 API 提供零值但防止崩溃,我需要它显示空。任何人都可以帮助解决 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?
}
}

所以我从你的问题中了解到的是你的 API 可能有数据,有时没有数据。这是 swift 中Optionals的行为。因此,您需要optional变量来存储数据。

NSDictionaryNSArray变量更改为optional可能会有所帮助。尝试以下代码:

class Instructors: UIViewController {
@IBOutlet var fullName: UILabel!
@IBOutlet var post: UILabel!
@IBOutlet var descriptionName: UITextView!
@IBOutlet var instructorImage: UIImageView!
var dictDataContent:NSDictionary?
var dictData:NSArray?
var dictprofile:NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
dictData = dictDataContent?.value(forKey: "instructors") as? NSArray
if let count = dictData?.count, count > 0 {
dictprofile = dictData?.object(at: 0) as? NSDictionary
}
if let urlString = dictprofile?.value(forKey: "profile_image") as? String {
if let url = URL(string: urlString) {
SDWebImageManager.shared().downloadImage(with: url, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if self != nil {
self?.instructorImage.image = image
}
})
}
}
fullName.text = dictprofile?.value(forKey: "full_name") as? String
post.text = dictprofile?.value(forKey: "designation") as? String
descriptionName.text = dictprofile?.value(forKey: "description") as? String
}
}

最新更新