【发布时间】:2020-11-06 11:15:37
【问题描述】:
假设我以编程方式在导航控制器中创建了一个 tableView。删除故事板文件及其参考后。我将所有 UI 初始化和约束代码放入loadView(),如下代码。
用真机运行,但是table view没有出现,很快就弹出这个警告。
如果我将这些代码放在viewDidLoad 中,一切正常。那么,我该如何追踪这个问题呢?我搜索了一些类似的线程,但没有解决我的问题。
警告:无法执行支持代码来读取 Objective-C 类数据 进行中。这可能会降低类型信息的质量 可用。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let table = UITableView()
var pictures = [Picture]()
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// if put code in loadView() into here, everything works fine.
loadData()
}
override func loadView() {
title = "My Pictures"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPicture))
view.addSubview(table)
table.delegate = self
table.dataSource = self
table.register(PictureCell.self, forCellReuseIdentifier: "picture")
table.translatesAutoresizingMaskIntoConstraints = false
table.rowHeight = 120
NSLayoutConstraint.activate([
table.topAnchor.constraint(equalTo: view.topAnchor),
table.leadingAnchor.constraint(equalTo: view.leadingAnchor),
table.trailingAnchor.constraint(equalTo: view.trailingAnchor),
table.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
func loadData() {
DispatchQueue.global().async { [weak self] in
if let savedPcitures = self?.defaults.object(forKey: "pictures") as? Data {
let jsonDecoder = JSONDecoder()
do {
self?.pictures = try jsonDecoder.decode([Picture].self, from: savedPcitures)
} catch {
print("Failed to load pictures.")
}
}
DispatchQueue.main.async {
self?.table.reloadData()
}
}
}
@objc func addPicture() {
let picker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.sourceType = .camera
} else {
fatalError("Camera is not available, please use real device")
}
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
...
【问题讨论】:
-
那你为什么不放viewDidLoad呢?您想知道为什么会发生这种情况或解决您的问题吗?