Created
November 20, 2019 03:55
-
-
Save karthikgs7/e836932f18b36a18f2b0e3824fef66c1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Foundation | |
import CoreData | |
public protocol Managed: class, NSFetchRequestResult { | |
static var entityName: String { get } | |
static var defaultSortDescriptors: [NSSortDescriptor] { get } | |
} | |
public extension Managed { | |
public static var defaultSortDescriptors: [NSSortDescriptor] { | |
return [] | |
} | |
static var sortedFetchRequest: NSFetchRequest<Self> { | |
let fetchRequest = NSFetchRequest<Self>(entityName: entityName) | |
fetchRequest.sortDescriptors = defaultSortDescriptors | |
return fetchRequest | |
} | |
} | |
extension NSManagedObjectContext { | |
func insert<T: Managed>() -> T { | |
let model = NSEntityDescription.insertNewObject(forEntityName: T.entityName, into: self) as! T | |
return model | |
} | |
func insertObject<A: NSManagedObject>() -> A where A:Managed { | |
guard let obj = NSEntityDescription.insertNewObject(forEntityName: A.entityName, into: self) as? A else { | |
fatalError("wrong object type") | |
} | |
return obj | |
} | |
public func saveOrRollback() -> Bool { | |
do { | |
try save() | |
return true | |
} | |
catch { | |
rollback() | |
return false | |
} | |
} | |
public func performChanges(block: @escaping () -> Void) { | |
perform { | |
block() | |
_ = self.saveOrRollback() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment