Skip to content

Instantly share code, notes, and snippets.

@deeje
Last active April 11, 2019 07:47
Show Gist options
  • Save deeje/0d01ad12a7064ffeb824892ba0b6dc0b to your computer and use it in GitHub Desktop.
Save deeje/0d01ad12a7064ffeb824892ba0b6dc0b to your computer and use it in GitHub Desktop.
DynamicCounter: Use FetchedResultsController to keep a dynamic count, the KVO
//
// DynamicCounter.swift
//
// Created by deeje cooley on 11/11/18.
// Copyright © 2018 deeje LLC. All rights reserved.
//
import CoreData
public class DynamicCounter: NSObject {
@objc dynamic public var count: Int = 0
fileprivate let moc: NSManagedObjectContext
fileprivate let frc: NSFetchedResultsController<NSFetchRequestResult>
init(container: NSPersistentContainer, entityName: String, predicate: NSPredicate? = nil) {
moc = container.newBackgroundContext()
moc.automaticallyMergesChangesFromParent = true
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
request.predicate = predicate ?? NSPredicate(value: true)
frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
super.init()
frc.delegate = self
try? frc.performFetch()
count = frc.fetchedObjects?.count ?? 0
}
}
extension DynamicCounter: NSFetchedResultsControllerDelegate {
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
count = frc.fetchedObjects?.count ?? 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment