I am trying to use Core Data and load a table view with its contents in order and in sections

137 Views Asked by At

I get it to load, I get the sections to load, but I cant get the cells in each section to load correctly. It restarts from the beginning in each section effectively duplicating each cell. My entity name is Customer and it holds the following attributes. firstName, lastName, phoneNumber,email, notes, and first. First is the first letter in the last name to use for the sections. I can get it to load, the headers load successfully but as soon as I start adding names with the same first letter in the last name, it starts messing up. Let me know if you need any more code.

override func tableView(tableView: UITableView,
        cellForRowAtIndexPath
        indexPath: NSIndexPath?) -> UITableViewCell
{

        //getSections()
        let cell =
        tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath!)

        let cust = customers[(indexPath?.section)!]
        print(indexPath?.row)
        let fName = cust.valueForKey("firstName") as? String
        print(fName)
        let lName = cust.valueForKey("lastName") as? String
        print(lName)
        cell.textLabel!.text = fName! + " " + lName!
        print("Cell: \(cell.textLabel!.text)")

        return cell


}
override func viewDidLoad() {
        super.viewDidLoad()


    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext
    context = managedContext

    //2
    let fetchRequest = NSFetchRequest(entityName:"Customer")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "lastName", ascending: true)]

    //3
    //var error: NSError?

    let fetchedResults = try!
        managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]

    if var results = fetchedResults
    {
        customers = results

    }
    else
    {
        print("Could not fetch")
    }

    tableView.reloadData()

    getSections()


}

    func getSections()
    {

    var sections:[String] = []
    for(var i=0;i<customers.count;i++)
    {
        let cust = customers[i]
        sections.append(cust.valueForKey("first") as! String)
    }
    sectionHeadersTotal = sections
    let unique = Array(Set(sections))
    sectionHeaders = unique.sort()
    print(sectionHeaders.count)
    //sectionHeaders = unique

    //return unique.count
}
1

There are 1 best solutions below

2
On BEST ANSWER