Created
July 7, 2020 15:44
-
-
Save stevencurtis/9a763d7e03a80f5e5c71390979490b1d to your computer and use it in GitHub Desktop.
coredatamanager
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
class CoreDataManager: CoreDataManagerProtocol { | |
private var tasks = [NSManagedObject]() | |
private var managedObjectContext: NSManagedObjectContext! = nil | |
private var entity: NSEntityDescription! = nil | |
init (objectContext: NSManagedObjectContext, entity: NSEntityDescription) { | |
self.managedObjectContext = objectContext | |
self.entity = entity | |
} | |
required init() { | |
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } | |
managedObjectContext = appDelegate.persistentContainer.viewContext | |
entity = NSEntityDescription.entity(forEntityName: Constants.entityName, in: managedObjectContext)! | |
} | |
func getTasks() -> [NSManagedObject] { | |
if tasks.count > 0 {return tasks} | |
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: Constants.entityName) | |
do { | |
tasks = try managedObjectContext.fetch(fetchRequest) | |
} catch let error as NSError { | |
print("Could not fetch. \(error), \(error.userInfo)") | |
} | |
return tasks | |
} | |
func save(task: String) { | |
let taskObject = NSManagedObject(entity: entity, insertInto: managedObjectContext) | |
taskObject.setValue(task, forKeyPath: Constants.entityNameAttribute) | |
do { | |
try managedObjectContext.save() | |
tasks.append(taskObject) | |
} catch let error as NSError { | |
print("Could not save. \(error), \(error.userInfo)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment