Group Group Group Group Group Group Group Group Group

Tableview not fetching core data date

My code when button btn is touched it should save the date and then display it on the tableview cell. Nothing is happening when the button is called. The code work in storyboard but it did not work when I programmed it. It does not make any sense. The code is not producing any errors. The code should have the day and time on the cell if it works.

import UIKit
 import CoreData

  class ViewController: UIViewController, UITableViewDataSource {


var table = UITableView()
var btn = UIButton()

var foodItems = [Food]()
var moc:NSManagedObjectContext!
var appDelegate = UIApplication.shared.delegate as? AppDelegate

override func viewDidLoad() {
    super.viewDidLoad()
    table.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    moc = appDelegate?.persistentContainer.viewContext
    self.table.dataSource = self
    
    
    loadData()
    btn.backgroundColor = .systemTeal
    [table,btn].forEach{
        view.addSubview($0)
        $0.translatesAutoresizingMaskIntoConstraints = false
    }
    NSLayoutConstraint.activate([
        
        
        
        table.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
        table.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
        table.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        table.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        
        btn.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
        btn.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
        btn.topAnchor.constraint(equalTo: view.topAnchor),
        btn.leadingAnchor.constraint(equalTo: view.leadingAnchor)
        
        
        
    ])
    btn.addTarget(self, action: #selector(addFoodToDatabase(_:)), for: .touchUpInside)
    
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadData()
}

func loadData(){
    // 1
    let foodRequest:NSFetchRequest<Food> = Food.fetchRequest()
    
    // 2
    let sortDescriptor = NSSortDescriptor(key: "added", ascending: false)
    foodRequest.sortDescriptors = [sortDescriptor]
    
    // 3
    do {
        try foodItems = moc.fetch(foodRequest)
        
    }catch {
        print("Could not load data")
    }
    
    // 4
    self.table.reloadData()
}



@objc   func addFoodToDatabase(_ sender: UIButton) {
    let foodItem = Food(context: moc)
    foodItem.added = NSDate() as Date
    
    
    
    appDelegate?.saveContext()
    
    loadData()
    
}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return foodItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    
    // 1
    let foodItem = foodItems[indexPath.row]
    
    // 2
    let foodType = foodItem.type
    cell.textLabel?.text = foodType
    
    // 3
    let foodDate = foodItem.added!
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMMM d yyyy, hh:mm"
    
    cell.detailTextLabel?.text = dateFormatter.string(from: foodDate)
    
    
    
    return cell
}




}

link to github

Hi @timswift, does your button call the action selector successfully? If so, is it the function loadData( ) that is not responding? Just trying to get a better understanding of what you mean by “nothing is happening when the button is called.”

Best,
Gina

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return commits.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: “Commit”, for: indexPath)

let commit = commits[indexPath.row]
cell.textLabel!.text = commit.message
cell.detailTextLabel!.text = commit.date.description

return cell

}

I got it it was the contview i needed to change. That was it.

1 Like