CoreData

PHOTO EMBED

Fri Apr 12 2024 06:27:34 GMT+0000 (Coordinated Universal Time)

Saved by @Saurabh_Lodhi #swift #coredata

// 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()
content_copyCOPY