Created
November 24, 2015 17:14
-
-
Save mingsai/64ee12684bc7eaff3a0a to your computer and use it in GitHub Desktop.
An example of using the NSFetchedResultsViewController in Swift 2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MNGNSFRVC.swift | |
// ProjectX | |
// | |
// Created by Tommie N. Carter, Jr., MBA on 11/15/15. | |
// Copyright © 2015 MING Technology. All rights reserved. | |
// | |
import UIKit | |
import CoreData | |
class MNGNSFRVC: UIViewController { | |
deinit { | |
} | |
//MARK: Outlets | |
@IBOutlet weak var tableView:UITableView! { | |
didSet { | |
tableView.tableFooterView = MNGStyleUtilities.sharedInstance.emptyView | |
} | |
} | |
@IBOutlet weak var spendingReport: UILabel! | |
@IBOutlet weak var communitySpendingTotal: UILabel! | |
//MARK: Class Variables | |
private var transactionTotal:Float = 0.0 | |
private var sectionTitles = [String]() | |
private var frc: NSFetchedResultsController? = nil | |
private lazy var fetchedResultsController:NSFetchedResultsController = { | |
if self.frc != nil { | |
return self.frc! | |
} | |
let moc = dbStore.sharedInstance.managedObjectContext | |
let fetchRequest = NSFetchRequest(entityName: "Transaction") | |
fetchRequest.fetchBatchSize = 30 | |
//let predicate = NSPredicate(format: "%K == %@", argumentArray: ["user", dbStore.sharedInstance.defaultUser]) | |
//fetchRequest.predicate = predicate | |
fetchRequest.resultType = NSFetchRequestResultType.ManagedObjectResultType | |
//storyFetchRequest.propertiesToFetch = ["assetURL","summary","title","tagsArray"] | |
let sortDescriptorByTimeStamp = NSSortDescriptor(key: "timeStamp", ascending: true) | |
fetchRequest.sortDescriptors = [sortDescriptorByTimeStamp] | |
//in-memory cache when cachename is nil, delegate is non-nil | |
let nfrc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: "category.categoryName", cacheName: nil) | |
//nfrc.delegate = self | |
self.frc = nfrc | |
do | |
{ | |
try self.frc!.performFetch() | |
} catch let e as NSError { | |
//print(e.localizedDescription) | |
fatalError(e.localizedDescription) | |
} | |
return self.frc! | |
}() | |
//MARK: View Lifecycle | |
override func prefersStatusBarHidden() -> Bool { | |
super.prefersStatusBarHidden() | |
return true | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
override func viewWillAppear(animated: Bool) { | |
super.viewWillDisappear(animated) | |
refreshTransactionTotal() | |
} | |
override func viewDidAppear(animated: Bool) { | |
super.viewDidAppear(animated) | |
} | |
override func viewWillLayoutSubviews() { | |
super.viewWillLayoutSubviews() | |
self.navigationItem.title = " Spend Summary " | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
// MARK: Action Methods | |
// MARK: Helper Methods | |
func refreshTransactionTotal () { | |
if self.fetchedResultsController.fetchedObjects?.count > 0 { | |
transactionTotal = dbStore.sharedInstance.calculateTransactionSummary((self.fetchedResultsController.fetchedObjects as! [Transaction])) | |
self.communitySpendingTotal.text = " Total: \(transactionTotal)" | |
} | |
} | |
// MARK: - Navigation | |
// In a storyboard-based application, you will often want to do a little preparation before navigation | |
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { | |
// Get the new view controller using segue.destinationViewController. | |
// Pass the selected object to the new view controller. | |
} | |
@IBAction func unwindToSpend (segue:UIStoryboardSegue) { | |
//refreshTransactionTotal() | |
self.view.layoutIfNeeded() | |
self.tableView.reloadData() | |
} | |
} | |
//MARK:TableView & FetchedResultsController Methods | |
extension SpendViewController:UITableViewDelegate,UITableViewDataSource, NSFetchedResultsControllerDelegate { | |
//MARK: TableView Sections | |
func numberOfSectionsInTableView(tableView: UITableView) -> Int { | |
print("# of sections: \(self.fetchedResultsController.sections?.count )") | |
let count = self.fetchedResultsController.sections?.count ?? 1 | |
return count | |
} | |
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { | |
return self.fetchedResultsController.sectionIndexTitles ?? [""] | |
} | |
//MARK: TableView Methods | |
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { | |
// | |
} | |
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return self.fetchedResultsController.sections![section].numberOfObjects ?? 0 | |
} | |
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCellWithIdentifier("TransactionCell", forIndexPath: indexPath) as! TransactionCell | |
configure(cell, transaction: self.fetchedResultsController.objectAtIndexPath(indexPath) as! Transaction) | |
// Configure the cell... | |
return cell | |
} | |
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { | |
let sectionTitle = self.fetchedResultsController.sections?[section].name ?? "No Category Titles" | |
return sectionTitle | |
} | |
func configure(cell:TransactionCell, transaction:Transaction) { | |
//deal with imag e thumbnail for transaction | |
//cell.imageView?.image | |
cell.businessName.text = transaction.business?.businessName ?? "No Business Added" | |
cell.amount.text = transaction.amount?.stringValue ?? "0.00" | |
cell.transactionDate.text = NSDateFormatter.localizedStringFromDate(transaction.transactionDate ?? NSDate(), dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.NoStyle) | |
if let rating = transaction.rating?.userRating { | |
cell.transactionRating.text = rating.stringValue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment