Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Core Data Helpers
//The following code depends on this:
//https://gist.github.com/sisoje/f1444dff45618938ce81324a81316690#file-nspredicate-keypath-operators-swift
import CoreData
extension NSManagedObject {
static var entityName: String {
return entity().name!
}
}
extension NSManagedObjectContext {
func insertObject<MO: NSManagedObject>() -> MO {
guard let obj = NSEntityDescription
.insertNewObject(forEntityName: MO.entityName, into: self) as? MO else {
fatalError("Entity \(MO.entityName) does not correspond to \(MO.self)")
}
return obj
}
func findFirst<MO: NSManagedObject, T: Equatable>(_ keyPath: KeyPath<MO, T>, _ value: T) throws -> MO? {
return try findFirst(keyPath == value)
}
func findFirst<MO: NSManagedObject>(_ predicate: NSPredicate) throws -> MO? {
let fetchRequest: NSFetchRequest<MO> = MO.fetchRequest() as! NSFetchRequest<MO>
fetchRequest.fetchLimit = 1
fetchRequest.predicate = predicate
return try fetch(fetchRequest).first
}
func findFirstOrCreate<MO: NSManagedObject, T: Equatable>(_ keyPath: ReferenceWritableKeyPath<MO, T>, _ value: T) throws -> MO {
if let existing = try findFirst(keyPath, value) {
return existing
}
let object = MO(context: self)
object[keyPath: keyPath] = value
return object
}
func findAll<MO: NSManagedObject, T: Equatable>(_ keyPath: KeyPath<MO, T>, _ value: T) throws -> [MO] {
let fetchRequest: NSFetchRequest<MO> = MO.fetchRequest() as! NSFetchRequest<MO>
fetchRequest.predicate = keyPath == value
return try fetch(fetchRequest)
}
}
extension NSFetchRequest {
@objc func filter(_ aPredicate: NSPredicate) -> NSFetchRequest<ResultType> {
if let existingPredicate = predicate {
self.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [existingPredicate, aPredicate])
} else {
self.predicate = aPredicate
}
return self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.