Skip to content

Instantly share code, notes, and snippets.

@marcos1262
Created October 27, 2018 13:42
Show Gist options
  • Save marcos1262/33a7d4b42afc68c79fdea4f4a12a28f0 to your computer and use it in GitHub Desktop.
Save marcos1262/33a7d4b42afc68c79fdea4f4a12a28f0 to your computer and use it in GitHub Desktop.
Nice functions for dealing with CoreData
//
// NSManagedObject.swift
//
// Created by Marcos Santos on 8/30/18.
// Copyright © 2018 Marcos Santos 2018. All rights reserved.
//
import Foundation
import CoreData
extension NSManagedObject {
convenience init(saving: Bool = true) throws {
let context = try DataManager.getContext()
if let entity = NSEntityDescription.entity(forEntityName: String(describing: type(of: self)), in: context) {
self.init(entity: entity, insertInto: saving ? context : nil)
} else {
throw Errors.wrongEntityName
}
}
public func insertIntoContext() throws {
if !self.isInserted {
let context = try DataManager.getContext()
context.insert(self)
}
}
public func delete() throws {
let context = try DataManager.getContext()
context.delete(self)
do {
try context.save()
} catch {
throw Errors.cantDeleteObject
}
}
public static func query(predicate: NSPredicate? = nil) throws -> [NSManagedObject] {
let context = try DataManager.getContext()
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = self.entity()
request.predicate = predicate
if let result = try? context.fetch(request){
if let resultObject = result as? [NSManagedObject]{
return resultObject
}
}
throw Errors.wrongFetch
}
public static func all() throws -> [NSManagedObject] {
return try query()
}
public static func deleteAll() throws {
let managedContext = try DataManager.getContext()
if let name = self.entity().name {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: name)
fetchRequest.returnsObjectsAsFaults = false
do{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
try managedContext.save()
} catch {
throw Errors.cantDeleteObject
}
} else {
throw Errors.wrongEntityName
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment