Created
October 27, 2018 13:42
-
-
Save marcos1262/33a7d4b42afc68c79fdea4f4a12a28f0 to your computer and use it in GitHub Desktop.
Nice functions for dealing with CoreData
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
// | |
// 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