json - 错误消息:在隐式展开可选值时意外发现 nil?
问题描述
我一直在尝试使用情节提要从 UICollectionView 中的 JSON 文件填充数据。创建网点后,我将图像和标签连接到 UICollectionViewCell.swift,将 Collection View 连接到 UICollectionView。但是,我收到一个错误,
在隐式展开 Optional 值时意外发现 nil:文件 Music2/ViewController.swift,第 22 行。
下面第 22 行指向“collectionView.dataSoure = self
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
parseJson()
}
之后,我解析了我的 JSON 文件并在 pasreJson() 的末尾添加了一个“DispatchQueue.main.async”(不确定该部分)。这会造成问题吗?
//JSON
private func parseJson(){
guard let path = Bundle.main.path(forResource: "data (1)", ofType: "json") else {
return
}
let url = URL(fileURLWithPath: path)
do{
let jsonData = try Data(contentsOf: url)
let userData = try JSONDecoder().decode(UserData.self, from: jsonData)
albums = userData.albums
playlists = userData.playlists
}catch{
print("error : \(error)")
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
这是我完整的视图控制器:
class ViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionView : UICollectionView!
//INSTANCE OF JSON DATA
var albums = [Album]()
var playlists = [Playlist]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
parseJson()
}
//UICollectionView protocols
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection
section: Int) -> Int {
return albums.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:
IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell",
for: indexPath) as! CollectionViewCell
cell.Label.text = albums[indexPath.row].title.capitalized
return cell
}
//JSON
private func parseJson(){
guard let path = Bundle.main.path(forResource: "data (1)", ofType: "json") else {
return
}
let url = URL(fileURLWithPath: path)
do{
let jsonData = try Data(contentsOf: url)
let userData = try JSONDecoder().decode(UserData.self, from: jsonData)
albums = userData.albums
playlists = userData.playlists
}catch{
print("error : \(error)")
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
解决方案
如果您在线上崩溃,collectionView.dataSource = self
那么您没有将集合视图连接到情节提要中的视图控制器。打开你的故事板并从集合视图控制拖动到视图控制器。
推荐阅读
- javascript - ScrollSpy 中的平滑滚动
- quarkus - 从 Quarkus 1.3.2.Final 迁移到 1.4.2.Final 影响 Vault 访问
- vue.js - Vue JS v-model 值更新不适用于点击事件
- c# - CheckBox 出现在 groupbox 后面
- r - 如何使用 r 提取 data.frame 的数组索引
- javascript - 了解document.documentElement.clientWidth/Height返回哪个视口,与window.innerHeight/innerWidth的区别
- json - 'flutter' 无法识别为 cmdlet 中的名称
- c++ - C++ 在构造函数初始化列表中初始化模板数组
- python - 4d np.array() 就像 1d np.array()
- python - 代理身份验证 selenium ERR_TUNNEL_CONNECTION_FAILED