【发布时间】:2019-01-10 00:15:30
【问题描述】:
从 CoreData 加载的数组中没有显示数据。
我已尝试打印语句以查看是否正在显示信息并查看导航控制器设置中另一个 ViewController 的代码。
这是一个小而简单的程序。此视图控制器包含在转到另一个视图控制器之前的类别,该视图控制器包含该类别中的数据/待办事项列表。
//
// CategoryViewController.swift
// Todoey
//
// Created by James Thomson on 06/01/2019.
// Copyright © 2019 James Thomson. All rights reserved.
//
import UIKit
import CoreData
class CategoryViewController: UITableViewController {
var categories = [Category]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
loadCategory()
self.tableView.reloadData()
super.viewDidLoad()
}
//MARK: - TableView Data Source Methods
override func numberOfSections(in tableView: UITableView) -> Int {
return categories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)
cell.textLabel?.text = categories[indexPath.row].name
return cell
}
//MARK: - Add New Categories
@IBAction func addBtnPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add Category", message:"", preferredStyle: .alert)
let action = UIAlertAction(title: "Add", style: .default) { (action) in // THIS IS A COMPLETION HANDLER
let newCategory = Category(context: self.context)
newCategory.name = textField.text!
self.categories.append(newCategory)
self.saveCategory()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create Category"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
print(categories)
}
//MARK: - TableView Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
//MARK: - Data Manipulation Methods (SAVE & LOAD)
func saveCategory() {
do {
try context.save()
} catch {
print("Save Category Error: \(error)")
}
DispatchQueue.main.async { self.tableView.reloadData() }
}
func loadCategory(with request: NSFetchRequest<Category> = Category.fetchRequest()) {
do {
categories = try context.fetch(request)
} catch {
print("Load Category Error: \(error)")
}
DispatchQueue.main.async { self.tableView.reloadData() }
}
}
尽管它们是数组中的数据,但该表当前显示为空白。
【问题讨论】:
-
您的应用程序是否曾经达到 numberOfSections/numberOfRows 函数?
-
当我设置断点并编译时,它到达VC显示之前。
标签: swift uitableview core-data