Home > Blockchain >  save increase int as multiple core data entities
save increase int as multiple core data entities

Time:03-14

In my swift code below I am trying to save ints to core data. Every time a user hits a button a new int is created. So if the user hits the button twice there are know 2 int entities in core data. My code below is having a runtime error and I dont know how to solve it.

pic

      var pageNumber = 0
        var itemName : [NSManagedObject] = []

   func enterData() {
    
    let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
    
    
    
    let context = appDeldeaget.persistentContainer.viewContext
    
    
    
    let entity = NSEntityDescription.entity(forEntityName: "Player", in: context)
    

    let theTitle = NSManagedObject(entity: entity!, insertInto: context)
 
    
    theTitle.setValue(pageNumber, forKey: "positon")
    
    do {
        try context.save()
        itemName.append(theTitle)
        pageNumber  = 1
        
     
    }
    catch {
        
    }
    self.theScores.reloadData()
    
 
            
  
    positionTextField.text = ""
    positionTextField.resignFirstResponder()
  
    
    
}

CodePudding user response:

You are introducing a few complications that might be causing the issue.

First, if I understood your purpose, the itemName should not be an array of NSManagedObject, but rather an array of Player. Also, creating the theTitle can be simplified.

Try this instead of the code you proposed:

      var pageNumber = 0

      // If I understand correctly, you should have an array of Players
      var itemName : [Player] = []

   func enterData() {
    
    let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
    
    let context = appDeldeaget.persistentContainer.viewContext
    
    // Simpler way to create a new Core Data object
    let theTitle = Player(context: context)

    // Simpler way to set the position attribute
    theTitle.position = pageNumber    // pageNumber must be of type Int64, otherwise use Int64(pageNumber)
    
    do {
        try context.save()
        itemName.append(theTitle)
        pageNumber  = 1
    } catch {
        // handle errors
    }
    
    // rest of the code

}
  • Related