如何解决Swift中的这个错误?
如何解决Swift中的这个错误?
在控制台中出现了以下错误:
当解包Optional值时,意外地发现了nil
并且在Xcode编辑器中显示以下错误:
THREAD 1 EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0*0)
我在Swift 3中有以下代码用于调用API并在视图中加载它:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.nameLabel!.text = nameArray[indexPath.row]
cell.dobLabel!.text = dobArray[indexPath.row]
cell.descLabel!.text = descArray[indexPath.row]
/*
let imgURL = NSURL(string: imgURLArray[indexPath.row])
let data = NSData(contentsOf: (imgURLArray as? URL)!)
cell.imageView!.image = UIImage(data: data as! Data)
*/
return cell
}
这是我的TableViewCell文件:
class TableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel?
@IBOutlet weak var descLabel: UILabel?
@IBOutlet weak var dobLabel: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
这是一个Swift代码片段,它包含了一个名为ApiViewController的UIViewController子类。在这个类中,有一个名为urlString的常量,用来保存一个URL字符串。还有一些数组用来保存从JSON数据中获取的信息。在viewDidLoad方法中,调用了downloadJsonWithURL方法,该方法用于从指定的URL下载JSON数据。在downloadJsonWithURL方法中,使用URLSession.shared.dataTask方法来进行网络请求,并尝试将返回的数据转换为NSDictionary类型的JSON对象。如果转换成功,就将actors数组保存到actorarray中,并刷新tableView。这段代码还包含了其他一些方法,用于设置tableView的行数和单元格内容。
这段代码中可能出现的问题是:
1. 在downloadJsonWithURL方法中,actorarray应该是self.actorarray,因为它是一个实例变量。
2. 在downloadJsonWithTask方法中,虽然创建了一个URLRequest对象,但没有使用该对象进行网络请求。
要解决这些问题,可以按照以下步骤进行修改:
1. 将downloadJsonWithURL方法中的actorarray = jsonObj!.value(forKey: "actors") as? NSArray修改为self.actorarray = jsonObj!.value(forKey: "actors") as? NSArray。
2. 在downloadJsonWithTask方法中,添加URLSession.shared.dataTask(with: downloadTask).resume()来执行网络请求。
修改后的代码如下:
import UIKit
class ApiViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
var nameArray = [String]()
var dobArray = [String]()
var imgURLArray = [String]()
var descArray = [String]()
var actorarray = NSArray()
weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "actors")!)
self.actorarray = jsonObj!.value(forKey: "actors") as? NSArray
self.tableView.reloadData()
}
}).resume()
}
func downloadJsonWithTask(){
let url = NSURL(string:urlString)
var downloadTask = URLRequest(url: (url as? URL)!,cachePolicy:URLRequest.CachePolicy.reloadIgnoringCacheData,timeoutInterval:20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask,completionHandler:{(data,response,error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData!)
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.actorarray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
let dic = self.actorarray[indexPath.row] as! NSDictionary
cell.nameLabel!.text = dic.object(forKey: "name") as! String
cell.dobLabel!.text = dic.object(forKey: "dob") as! String
cell.descLabel!.text = dic.object(forKey: "image") as! String
return cell
}
}
希望这些修改能够解决问题。