I have been using SwiftyJSON to create my models of Object in Swift. But recently, I moved to CoreData for saving the objects locally. I am new to CoreData and want to know the best practices I should follow for creating the model.
Here's what I have created to update and get User's data (after getting the JSON from webservice)
Core Data Model
import Foundation
import CoreData
import SwiftyJSON
@objc(User)
public class User: NSManagedObject {
var authToken : String!
class func addUser(fromJSON json: JSON?, inManagedObjectContext managedObjectContext: NSManagedObjectContext?) -> User? {
if var json = json { //unwrapping
let entityDescription = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext!)
let newUser = NSManagedObject(entity: entityDescription!, insertInto: managedObjectContext) as! User
json = json["user"]
newUser.authToken = json["auth_token"].stringValue
newUser.email = json["email"].stringValue
managedObjectContext?.perform({
_ = try? newUser.managedObjectContext!.save()
})
return newUser
}
return nil
}
class func getUser(inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> User? {
// Initialize Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
// Create Entity Description
let entityDescription = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext)
// Configure Fetch Request
fetchRequest.entity = entityDescription
if let result = try? managedObjectContext.fetch(fetchRequest) {
return result.first as? User
} else {
return nil
}
}
class func updateUser(fromJson json : JSON?, inManagedObjectContext managedObjectContext: NSManagedObjectContext) {
let user = getUser(inManagedObjectContext: managedObjectContext)
if var json = json {
json = json["user"]
user?.name = json["name"].stringValue
user?.email = json["email"].stringValue
}
managedObjectContext.perform({
_ = try? managedObjectContext.save()
})
}
}
Here's how I used to create model before I was using Core Data:
Previous Model
import Foundation
import SwiftyJSON
class User : NSObject, NSCoding{
var email : String!
var name : String!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json == nil{
return
}
email = json["email"].stringValue
name = json["name"].stringValue
}
}
Although the code is working, I am not sure if this is the right way to do it. How should I actually create the model with CoreData? And how should I call them from ViewControllers? I tried reading tutorials, but they help on getting started but not on how to use them in bigger projects.