-
-
Save kashiash/6187eec15f3436e211c81a912b81c316 to your computer and use it in GitHub Desktop.
CoreDataManager cheatsheet
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 CoreData | |
| import UIKit | |
| // ./NoteList.xcdatamodeld | |
| class CoreDataManager { | |
| static let sharedInstance = CoreDataManager() | |
| private init() { } | |
| lazy var persistentContainer: NSPersistentContainer = { | |
| let container = NSPersistentContainer(name: "NoteList") | |
| container.loadPersistentStores(completionHandler: { (storeDescription, error) in | |
| if let error = error as NSError? { | |
| fatalError("Unresolved error \(error), \(error.userInfo)") | |
| } | |
| }) | |
| return container | |
| }() | |
| func fetchAllNotes() -> [Note] { | |
| let fetchRequest: NSFetchRequest<Note> = Note.fetchRequest() | |
| let context = persistentContainer.viewContext | |
| guard let results = try? context.fetch(fetchRequest) else { | |
| return [] | |
| } | |
| return results | |
| } | |
| func createNote(for title: String, content: String) { | |
| let managedObjectContext = persistentContainer.viewContext | |
| let note = Note(context: managedObjectContext) | |
| note.title = title | |
| note.content = content | |
| note.createdDate = Date() | |
| note.id = UUID() | |
| do { | |
| try managedObjectContext.save() | |
| } catch { | |
| print(error) | |
| } | |
| } | |
| func fetchNote(for id: UUID) -> Note? { | |
| let predicate = NSPredicate(format: "id == %@", id as CVarArg) | |
| let fetchRequest: NSFetchRequest<Note> = Note.fetchRequest() | |
| fetchRequest.predicate = predicate | |
| let context = persistentContainer.viewContext | |
| guard let results = try? context.fetch(fetchRequest) else { | |
| return nil | |
| } | |
| return results.first | |
| } | |
| func delete(for noteId: UUID) { | |
| guard let note = fetchNote(for: noteId) else { | |
| return | |
| } | |
| let context = persistentContainer.viewContext | |
| do { | |
| context.delete(note) | |
| try context.save() | |
| } catch { | |
| print("Error saving: \(error)") | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment