核心数据可打印已保存的数据,但不会显示在表ViewController上

时间:2018-09-10 03:27:27

标签: swift

我想在表格视图控制器上的核心数据中显示我保存的数据,数据已正确保存并在控制台上打印出详细信息,但是数据没有显示在表格视图单元中,请提供帮助

var charData = [SavedCharacters]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var name = String()
var house = String()
var ancestry = String()
var getImage = UIImage()
override func viewDidLoad() {
    super.viewDidLoad()
    getData()
}
func getData(){
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "SavedCharacters")
    request.returnsObjectsAsFaults = false
    do{
        let result = try? context.fetch(request)
        for data in result as! [NSManagedObject]
        {
            name = data.value(forKey: "name") as! String

            print(data.value(forKey: "name")as! String)
        }
    }
    tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return charData.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "dataCell", for: indexPath) as! SavedDataTableViewCell

    cell.nameLabel.text = charData[indexPath.row].name!
    cell.house = charData[indexPath.row].house!
    cell.ancestry = charData[indexPath.row].ancestry!
    // displaying image in table view cell
    if let imageURL = URL(string: self.charData[indexPath.row].image!) {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL)
            if let data = data {
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    cell.charImageView.image = image
                }
            }
        }
    }
    return cell
}

1 个答案:

答案 0 :(得分:2)

您肯定已经忘记在getData()方法中初始化charData

var charData: [CharData]

func getData(){

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "SavedCharacters")
    request.returnsObjectsAsFaults = false

    ====> charData = []

    do{
        let result = try? context.fetch(request)
        for data in result as! [CharData]
        {
            name = data.value(forKey: "name") as! String

            print(data.value(forKey: "name")as! String)

            ===> charData.append(data)
        }
    }
    tableView.reloadData()
}