Skip to content

Instantly share code, notes, and snippets.

@nazywamsiepawel
Created July 2, 2018 14:38
Show Gist options
  • Save nazywamsiepawel/eeed3fa716719518420488b32ce79a22 to your computer and use it in GitHub Desktop.
Save nazywamsiepawel/eeed3fa716719518420488b32ce79a22 to your computer and use it in GitHub Desktop.
Some useful core data extensions + threading
import UIKit
import CoreData
public class Mappable : NSManagedObject {
var className: String {
return String(describing: type(of: self))
}
class var className: String {
return String(describing: self)
}
static var entityName: String {
return self.className //insead of `entity().name!`
}
func mapProperties(_ dict:NSDictionary) {
}
class func create(context:NSManagedObjectContext) -> Mappable {
let entityName = self.entityName
let entity = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Mappable
return entity
}
class func upsert(predicate:NSPredicate, context:NSManagedObjectContext, data:NSDictionary) -> Mappable {
if let entity = fetch(withPredicate: predicate, inContext: context)?.first {
entity.mapProperties(data)
return entity
} else {
let newEntity = create(context: context)
newEntity.mapProperties(data)
return newEntity
}
}
private class func fetch(fetchRequest:NSFetchRequest<NSFetchRequestResult>, context:NSManagedObjectContext) -> [Mappable]?{
do {
let results = try context.fetch(fetchRequest) // TODO : this errors out
let entities = results as! [Mappable]
if results.count == 0 {
return nil
} else {
return entities
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return nil
}
}
class func fetchAll(inContext context:NSManagedObjectContext) -> [Mappable]? {
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
return self.fetch(fetchRequest: fetchRequest, context: context)
}
class func fetch(withPredicate predicate:NSPredicate, inContext context:NSManagedObjectContext) -> [Mappable]? {
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.predicate = predicate
return self.fetch(fetchRequest: fetchRequest, context: context)
}
class func fetch(_ property:String, _ value:String, _ context:NSManagedObjectContext) -> Mappable? {
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let predicate: NSPredicate = NSPredicate(format: "\(property) == %@", value)
fetchRequest.predicate = predicate
return self.fetch(fetchRequest: fetchRequest, context: context)?.first
}
func inContext(context:NSManagedObjectContext) -> Mappable? {
var objectID = self.objectID
if let entity = context.object(with: objectID) as? Mappable {
return entity
} else {
return nil
}
}
class func count(context:NSManagedObjectContext) -> Int {
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
//var predicate = NSPredicate(format: "status != 'Read' && fromBarchick == YES")
//fetchRequest.predicate = predicate
let count = try! context.count(for: fetchRequest)
return count
}
class func count(predicate:NSPredicate, context:NSManagedObjectContext) -> Int {
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.predicate = predicate
let count = try! context.count(for: fetchRequest)
return count
}
class func delete(_ property:String, _ value:String, _ context:NSManagedObjectContext) {
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let predicate: NSPredicate = NSPredicate(format: "\(property) == %@", value)
fetchRequest.predicate = predicate
do
{
let results = try context.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
context.delete(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entityName) error : \(error) \(error.userInfo)")
}
}
class func deleteAll(){
let managedContext = Cholent.getContext()
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entityName) error : \(error) \(error.userInfo)")
}
}
class func deleteAll(context:NSManagedObjectContext){
let managedContext = context
let entityName = self.entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entityName) error : \(error) \(error.userInfo)")
}
}
}
class Cholent {
var mainContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
class func getContext() -> NSManagedObjectContext {
return (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
}
func saveContext(){
self.mainContext.performAndWait {
do {
try self.mainContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
func perform(operation:@escaping (_ context:NSManagedObjectContext) -> (), completed:@escaping ()->()) {
let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
backgroundContext.parent = mainContext
backgroundContext.perform {
operation(backgroundContext)
do {
try backgroundContext.save()
self.mainContext.performAndWait {
do {
try self.mainContext.save()
completed()
} catch {
fatalError("Failure to save context: \(error)")
}
}
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment