Core Data Make Decodable

So I am using core data and I have to make my class Decodable to use the decoder for my get request. The errors I get are 'self' used in property access before 'super.init' call in my CoreDataClass each of my decode values has the error.

CoreDataProperties

Code Block
extension CurrentPlayers {
  @nonobjc public class func fetchRequest() -> NSFetchRequest<CurrentPlayers> {
    return NSFetchRequest<CurrentPlayers>(entityName: "CurrentPlayers")
  }
  @NSManaged public var photoUrl: String?
  @NSManaged public var firstName: String?
  @NSManaged public var lastName: String?
  @NSManaged public var position: String?
  @NSManaged public var team: String?
  @NSManaged public var yahooName: String?
  @NSManaged public var status: String?
  @NSManaged public var jerseyNumber: Int64
}
extension CurrentPlayers : Identifiable {
}


CoreDataClass

Code Block
@objc(CurrentPlayers)
public class CurrentPlayers: NSManagedObject, Decodable {
   
  enum CodingKeys: String, CodingKey {
    case photoUrl = "PhotoUrl"
    case firstName = "FirstName"
    case lastName = "LastName"
    case position = "Position"
    case team = "Team"
    case yahooName = "YahooName"
    case status = "Status"
    case jerseyNumber = "JerseyNumber"
  }
   
  required public init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    photoUrl = try values.decode(String.self, forKey: CodingKeys.photoUrl)
    firstName = try values.decode(String.self, forKey: CodingKeys.firstName)
    lastName = try values.decode(String.self, forKey: CodingKeys.lastName)
    position = try values.decode(String.self, forKey: CodingKeys.position)
    team = try values.decode(String.self, forKey: CodingKeys.team)
    yahooName = try values.decode(String.self, forKey: CodingKeys.yahooName)
    status = try values.decode(String.self, forKey: CodingKeys.status)
    jerseyNumber = Int64(try values.decode(Int.self, forKey: CodingKeys.jerseyNumber))
  }
}

Answered by OOPer in 665682022
Seems you do not think PlayersVC or cPlayerArr is related...

OK, I can guess, just that makes me spend more time.
Code Block
        let decoder = JSONDecoder()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate //<- Intentionally using forced casting.
        decoder.userInfo[.managedObjectContext] = appDelegate.persistentContainer.viewContext




Searching with "Core Data Make Decodable", I could have find this article:
Using Codable with Core Data and NSManagedObject
(Seems the dev forums does not like this URL and I cannot include the link to it. Please search with the title.)

The core part of the article is to put the line calling init(context:) into the initializer init(from:):
Code Block
enum DecoderConfigurationError: Error {
case missingManagedObjectContext
}
extension CodingUserInfoKey {
static let managedObjectContext = CodingUserInfoKey(rawValue: "managedObjectContext")!
}
@objc(CurrentPlayers)
public class CurrentPlayers: NSManagedObject, Decodable {
enum CodingKeys: String, CodingKey {
case photoUrl = "PhotoUrl"
case firstName = "FirstName"
case lastName = "LastName"
case position = "Position"
case team = "Team"
case yahooName = "YahooName"
case status = "Status"
case jerseyNumber = "JerseyNumber"
}
public static var managedObjectContext: NSManagedObjectContext?
required public convenience init(from decoder: Decoder) throws {
guard let context = decoder.userInfo[.managedObjectContext] as? NSManagedObjectContext else {
throw DecoderConfigurationError.missingManagedObjectContext
}
self.init(context: context)
//...
}
}


You just need to pass the right managed object context when decoding:
Code Block
let decoder = JSONDecoder()
decoder.userInfo[.managedObjectContext] = ...
decoder.decode(...)


Okay so I have to modify my get request then.

Okay so I have to modify my get request then.

Maybe.

I'm having trouble adding this line to my request      
decoder.userInfo[.managedObjectContext] = persistentContainer.viewContext()
it tells me it doesn't find persistentContainer in scope even though I had persistent container declared in my appDelegate file.

Code Block
   // MARK: CoreData
  lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "playerModel")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
      if let error = error as NSError? {
        fatalError("Unresolved error \(error), \(error.userInfo)")
      }
    })
    return container
  }()



it tells me it doesn't find persistentContainer in scope even though I had persistent container declared in my appDelegate file.

It depends where you wrote the line decoder.userInfo[.managedObjectContext] = persistentContainer.viewContext().
Please show enough context.
It's in another file I call PlayersVC. I have it written in my get request method in the beginning before the receive data process.

It's in another file I call PlayersVC. I have it written in my get request method in the beginning before the receive data process.

So, what?

Please show enough context.

If you do not want to show enough context, please say so.
I can show you the method but I will have to remove the API key.

Code Block
func parseJSON(completed: @escaping () -> ()) {
    let url = URL(string: "WebsiteLink")
    let decoder = JSONDecoder()
    decoder.userInfo[.managedObjectContext] = persistentContainer.viewContext() //persistentContainer not in scope
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
       
      if error == nil {
        do {
          self.cPlayerArr = try JSONDecoder().decode([CurrentPlayers].self, from: data!)
          let json = try JSONSerialization.jsonObject(with: data!, options: [])
          print(json)
           
          DispatchQueue.main.async {
            completed()
          }
        } catch {
          print("JSON Error: ", error)
        }
      }
       
    }.resume()
  }

I can show you the method but I will have to remove the API key.

Thanks for showing additional code, and it's OK I do not need API key.

But what I want is context. In which class you defined the method? Please show whole definition of the class, including the definitions of all related properties and methods.
This is the whole class and related methods.


Code Block
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
   
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
  }
  // MARK: UISceneSession Lifecycle
  func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  }
  func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  }
   
   
  // MARK: CoreData
  lazy var persistentContainer: NSPersistentContainer = {
    */
    let container = NSPersistentContainer(name: "playerModel")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
      if let error = error as NSError? {
        fatalError("Unresolved error \(error), \(error.userInfo)")
      }
    })
    return container
  }()
   
  func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
      do {
        try context.save()
      } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
      }
    }
  }
}




Accepted Answer
Seems you do not think PlayersVC or cPlayerArr is related...

OK, I can guess, just that makes me spend more time.
Code Block
        let decoder = JSONDecoder()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate //<- Intentionally using forced casting.
        decoder.userInfo[.managedObjectContext] = appDelegate.persistentContainer.viewContext




Alright thank you I was able to fix my other issues so I can close this thread.
Core Data Make Decodable
 
 
Q