将按日期分隔的部分添加到Swift CoreData中的UITableView

时间:2015-01-09 12:02:57

标签: uitableview swift core-data sections

有人可以告诉我如何使用CoreData添加带日期的部分吗?

我有detailViewController,它存储来自CoreDate的所有数据,以及当我们写一些数据时AddTableViewController。

详情视图控制器

import UIKit

import CoreData

class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, AddTableViewControllerDelegate {

@IBOutlet weak var tableView: UITableView!

var detailTaskModel: Items!
var costsValues:Int!


@IBOutlet weak var sumLabel: UILabel!

// CoreData
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController()



override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.delegate = self
    self.tableView.dataSource = self

    fetchedResultsController = getFetchedResultsController()
    fetchedResultsController.delegate = self
    fetchedResultsController.performFetch(nil)

    costsValues = getAccountCountSum()
    self.tableView.reloadData()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


// UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController.sections![section].numberOfObjects
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: DetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("detailCell") as DetailTableViewCell
    let thisCost = fetchedResultsController.objectAtIndexPath(indexPath) as Costs

    cell.nazwaWydatkuLabel.text = thisCost.costsName
    cell.wartośćLabel.text = "\(thisCost.costsValue) zł"

    return cell
}

@IBAction func addCostButtonPressed(sender: UIBarButtonItem) {

   self.performSegueWithIdentifier("addCostVC", sender: self)
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return fetchedResultsController.sections!.count
}

override func viewDidAppear(animated: Bool) {
    costsValues = getAccountCountSum()
    refreshTable()
    self.tableView.reloadData()
}

// CoreData Functions
func taskFetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Costs")
    let sortDescriptor = NSSortDescriptor(key: "costsDate", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

func getFetchedResultsController() -> NSFetchedResultsController {
    fetchedResultsController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
    return fetchedResultsController
}

// NSFetchedResultsControllerDelegate
func controllerDidChangeContent(controller: NSFetchedResultsController) {
    tableView.reloadData()
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    let thisCost = fetchedResultsController.objectAtIndexPath(indexPath) as Costs
    managedObjectContext?.deleteObject(thisCost)
    costsValues = getAccountCountSum()

    refreshTable()
    self.tableView.reloadData()
    (UIApplication.sharedApplication().delegate as AppDelegate).saveContext()
}

// Sum count in all accouts
func getAccountCountSum() -> Int {
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
    var fetchRequest = NSFetchRequest(entityName: "Costs")
    fetchRequest.returnsObjectsAsFaults = false
    var results: NSArray = managedContext.executeFetchRequest(fetchRequest, error: nil)!

    var accountsSum: Int = 0
    for res in results {
        var accountCount = res.valueForKey("costsValue") as Int
        accountsSum += accountCount
    }
    self.sumLabel.text = String("\(costsValues) zł")
    return accountsSum
}

func refreshTable() {
    getAccountCountSum()
    self.tableView.reloadData()
}

}

AddTableViewController

    @IBAction func saveButtonTapped(sender: UIBarButtonItem) {

    // CoreData Access
    let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var managedObjectContext = appDelegate.managedObjectContext
    let entityDescription = NSEntityDescription.entityForName("Costs", inManagedObjectContext: managedObjectContext!)

    let cost = Costs(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)

    cost.costsName = cellThreeNoteTextField.text
    cost.costsValue = (cellOnePriceTextField.text).toInt()!
    cost.costsDate = datePicker.date

    // Saving data
    appDelegate.saveContext()

    var request = NSFetchRequest(entityName: "Costs")
    var error:NSError? = nil

    var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!

    for res in results {
        println(res)

    }
    delegate?.refreshTable()
    self.navigationController?.popViewControllerAnimated(true)

}

1 个答案:

答案 0 :(得分:1)

由于您使用的是NSFetchedResultsController,因此可以通过将托管对象上的密钥传递给sectionNameKeyPath参数来创建部分。然后,获取的结果控制器的sections属性将根据获取的对象中该键路径的值将结果分解为多个部分。

您还需要实施UITableView次回调以使其使用这些部分 - 例如sectionIndexTitlesForTableViewtableView:titleForHeaderInSection:。这些在NSFetchedResultsController文档中进行了描述。