我正在使用TabbarController来显示3个xib。我想在UITabBarController子类中解码JSON数据,然后与视图控制器共享数据(据我所知,这样做是首选的方法)。我已经在每个视图控制器中分别成功地完成了此任务,在该视图控制器中,相同的JSON数据分别进行了3次解码,但是现在我试图通过仅处理JSON一次来提高处理效率。
我当前遇到以下错误
“线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7ffee7ab7d98)”。
以下是我当前正在使用的代码。我主要只包含第一个视图控制器的代码,而其他视图控制器则相同
这里是视图控制器之一。任何帮助将不胜感激,谢谢!
class FirstCollectionViewController: UIViewController {
var tbvc = CustomTabBar()
var statisticsData = [Model]()
let firstCellIdentifier = "FirstCellIdentifier"
@IBOutlet weak var FirstCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
FirstCollectionView.delegate = self
FirstCollectionView.dataSource = self
FirstCollectionView.register(UINib(nibName: "FirstCollectionViewCell", bundle: nil),forCellWithReuseIdentifier: firstCellIdentifier)
}
}
这是UITabBarController的子类
import UIKit
class CustomTabBar: UITabBarController {
let website = "https:......."
var statisticsData = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
let firstTab = FirstCollectionViewController(nibName: "FirstCollectionViewController", bundle: nil)
let secondTab = SecondCollectionViewController(nibName: "SecondCollectionViewController", bundle: nil)
let thirdTab = ThirdCollectionViewController(nibName: "ThirdCollectionViewController", bundle: nil)
viewControllers = [firstTab, secondTab, thirdTab]
downloadJSON(website: website) {
firstTab.statisticsData = self.statisticsData
secondTab.statisticsData = self.statisticsData
thirdTab.statisticsData = self.statisticsData
firstTab.FirstCollectionView.reloadData()
secondTab.SecondCollectionView.reloadData()
thirdTab.ThirdCollectionView.reloadData()
}
}
func downloadJSON(website:String, completed:@escaping ()->()){
guard let qurl = URL(string: website) else { return }
URLSession.shared.dataTask(with: qurl) { (data, response, error) in
if error == nil {
do{
self.statisticsData = try JSONDecoder().decode([Model].self, from: data!)
DispatchQueue.main.async{
completed()
}
} catch {
print("JSON Error")
}}
}.resume()
}
}
答案 0 :(得分:0)
一旦加载了数据,您应该将数据分配给viewControllers
子列表中添加的tabBarController's
,如下所示,
downloadJSON(website: website) {
firstTab.statisticsData = self.statisticsData
secondTab.statisticsData = self.statisticsData
thirdTab.statisticsData = self.statisticsData
firstTab.FirstCollectionView.reloadData()
secondTab.SecondCollectionView.reloadData()
thirdTab.ThirdCollectionView.reloadData()
}
您还可以从viewDidLoad
,FirstCollectionViewController
和SecondCollectionViewController
的{{1}}中删除以下几行
ThirdCollectionViewController