Last active
April 11, 2019 07:47
-
-
Save deeje/0d01ad12a7064ffeb824892ba0b6dc0b to your computer and use it in GitHub Desktop.
DynamicCounter: Use FetchedResultsController to keep a dynamic count, the KVO
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
// | |
// 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