// Create a data model file // -> Create entity and attributes // -> Set the Codegen property of Entity as Manual/None // -> Select the Entity, Under Editor -> Create NSManagedObject Classes //Create a CoreDataManager file import Foundation import CoreData final class CoreDataManager{ static let shared = CoreDataManager(modelName: "UserModel_CD") let persistentContainer: NSPersistentContainer var viewContext: NSManagedObjectContext{ return persistentContainer.viewContext } init (modelName: String){ persistentContainer = NSPersistentContainer(name: modelName) } func load(completion: (() -> Void)? = nil) { persistentContainer.loadPersistentStores { (description, error) in guard error == nil else { fatalError(error!.localizedDescription) } completion?() } } func save(){ if viewContext.hasChanges{ do{ try viewContext.save() }catch{ print("Error While Saving Data !!!") } } } } //Inside App delegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch CoreDataManager.shared.load() return true } // Extension that is application specific !!! here the changes are made extension CoreDataManager{ //Perform Your CRUD Here !!! func createUser(with email: String, and password: String){ let user = UserModel_CD(context: viewContext) user.email = email user.password = password do{ try viewContext.save() }catch{ print(error.localizedDescription) } } func getAllUser() -> [UserModel_CD]{ do{ return try viewContext.fetch(UserModel_CD.fetchRequest()) }catch{ print(error.localizedDescription) return [] } } func updateUser(user: UserModel_CD, updatedUser: UserModel_CD){ user.email = updatedUser.email user.password = updatedUser.password do{ try viewContext.save() }catch{ print(error.localizedDescription) } } func deleteUser(user: UserModel_CD){ viewContext.delete(user) } } //access this method like - CoreDataManager.shared.create()
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter