jweaver60
7/20/2016 - 2:20 PM

Core Data Table View

Core Data Table View

// Model

import Foundation
import CoreData
import DATAStack

@objc(Lead)
class Lead: NSManagedObject {
    @NSManaged var id: Int
    @NSManaged var firstName: String?
    @NSManaged var lastName: String?
    @NSManaged var quotedPrice: String?
    
    class func getAllFromDatabase() -> [Lead] {
        var leads = [Lead]()
        
        let dataStack = DATAStack(modelName: "LeadsApp")
        let fetchRequest = NSFetchRequest()
        let entityDescription = NSEntityDescription.entityForName("Lead", inManagedObjectContext: dataStack.mainContext)
        
        fetchRequest.entity = entityDescription
        
        do {
            let result = try dataStack.mainContext.executeFetchRequest(fetchRequest)
            leads = result as! [Lead]
        } catch {
            let fetchError = error as NSError
            print(fetchError)
        }
        
        return leads
    }
}


// TableViewController

import UIKit

class DashboardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    var refreshControl: UIRefreshControl!
    var leadData = [Lead]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.refreshControl = UIRefreshControl()
        self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        self.refreshControl.addTarget(self, action: #selector(DashboardViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
        self.tableView.addSubview(refreshControl)
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        fetchLatestLeads()
    }
    
    func fetchLatestLeads() {
        // fetch leads from CoreData
        self.leadData = Lead.getAllFromDatabase()
        self.tableView.reloadData()
    }
    
    func refresh(sender: AnyObject) {
        fetchLatestLeads()
        self.refreshControl.endRefreshing()
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.leadData.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("leadCell", forIndexPath: indexPath)
        
        let lead = self.leadData[indexPath.row]
        
        cell.textLabel?.text = lead.firstName
        cell.detailTextLabel?.text = lead.quotedPrice
        
        return cell
    }
}