Get updates on your email

Wednesday, November 7, 2018

CRUD Core Data Example

Make a new project and you don't need to check core data for now we will tell you another way to add a data file.


Here is an example:

We will have two entities. First one is user and the other one is called as cars. It'll be a one to many relationship, which means a user can have multiple cars but a car will have one user.

Or another example would a game log. Which means a user can play multiple game but a game will be played by only one user. So this is a one to many relationship.

Go ahead and add a new file and select DataModel name is and save it in the project.


Add entities and attributes, give types to attributes and make relationships.

In your AppDelegate.swift after var window: UIWindow? add this code:

lazy var persistentContainer: NSPersistentContainer = {
        
        let container = NSPersistentContainer(name: "NameOfDataModel")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {
                
                fatalError("Unresolved error, \((error as NSError).userInfo)")
            }
        })
        return container

    }()

Go to your ViewController.swift and assign this variable:

let appDelegate = UIApplication.shared.delegate as? AppDelegate

Let's create a function where we will check if a use exist or not, if they do exist then add the new game data to their record and if they don't exist then make a new user and then add the game data for them.
_______________________________________________________________
func saveEverything() {
        
        let managedContext = appDelegate?.persistentContainer.viewContext
        let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "UsersLog")
        fetchRequest.predicate = NSPredicate(format: "email = %@""my@email.com") //this will search the records based on the email
        
        do {
            let fetchUser = try managedContext?.fetch(fetchRequest)
             //if fetchuser found something it's count will be greater than one
            if (fetchUser?.count ?? 0 > 0) {
                //picking up the first result
                let foundedUserLog = fetchUser?[0] as! NSManagedObject
                
                foundedUserLog.setValue(user?.email, forKey: "email")
                foundedUserLog.setValue(user?.displayName, forKey: "fullName")
                
//creating a new game log entity for the found user
                let gameLogEntity = NSEntityDescription.entity(forEntityName: "GameLog", in: managedContext!)! 
//creating a new object to add game data
                let gameLog = NSManagedObject(entity: gameLogEntity, insertInto: managedContext)
                let date = Date()
                
                gameLog.setValue(date, forKey: "logEntryDate")
                gameLog.setValue(finalScore, forKey: "finalScore")
                //This is the only line that is different. Here we are giving the founded user
                gameLog.setValue(foundedUserLog, forKey: "userID")
                
//saving data
                do {
                    try managedContext?.save()
                } catch {
                    print(error)
                }
                
            } else {

//create a new entity and object for user
                let userEntity = NSEntityDescription.entity(forEntityName: "UsersLog", in: managedContext!)!
                let newUserLog = NSManagedObject(entity: userEntity, insertInto: managedContext)
                
               
                newUserLog.setValue(user?.email, forKey: "email")
                newUserLog.setValue(user?.displayName, forKey: "fullName")
                
                let gameLogEntity = NSEntityDescription.entity(forEntityName: "GameLog", in: managedContext!)!
                let gameLog = NSManagedObject(entity: gameLogEntity, insertInto: managedContext)
                let date = Date()
                
                gameLog.setValue(date, forKey: "logEntryDate")
                gameLog.setValue(finalScore, forKey: "finalScore")
                gameLog.setValue(newUserLog, forKey: "userID")
                
                do {
                    try managedContext?.save()
                } catch {
                    print(error, error.localizedDescription)
                }
                
            }
        } catch {
            print(error)
        }

    }

_______________________________________________________________

Now that you have saved the data here is how you can retrieve it:
Go to your scoreboardViewController.swift and make a new variable

let appDelegate = UIApplication.shared.delegate as? AppDelegate

func retriveUserData() {
        let managedContext = appDelegate?.persistentContainer.viewContext
        let userFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UsersLog")
        userFetchRequest.predicate = NSPredicate(format: "email = %@""my@email.com")
        
        do {
            let fetchUser = try managedContext?.fetch(userFetchRequest)
            if (fetchUser?.count ?? 0 > 0) {
                let foundedUser: UsersLog = fetchUser?.first as! UsersLog
                let userGames = foundedUser.game?.allObjects as! [GameLog] //you can loop to get data from all the games
                tempTextView.text = "Name: \(foundedUser.fullName ?? "Name not Found") has played \(userGames.count) games"
                
            } else {
                tempTextView.text = "This user haven't played any games yet."
            }
        } catch {
            print(error)
        }


    }

Other than that here are the basic crud functions:








No comments:

Post a Comment