CoreData Swift: How to save and load data?
Swift 5
Step 1. Create Simple app with CoreData option
Step 2. Open .xcdatamodeld file and add Entity, Attributes this way
Step 3. your AppDelegate should have Core Data stack methods
Step 4. Make sure you have swift code snipe as following
import UIKit
import CoreData
class ViewController: UIViewController {
// MARK: Variables declearations
let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
var context:NSManagedObjectContext!
// MARK: View Controller life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
openDatabse()
}
// MARK: Methods to Open, Store and Fetch data
func openDatabse()
{
context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
saveData(UserDBObj:newUser)
}
func saveData(UserDBObj:NSManagedObject)
{
UserDBObj.setValue("RDC", forKey: "username")
UserDBObj.setValue("1234", forKey: "password")
UserDBObj.setValue("21", forKey: "age")
print("Storing Data..")
do {
try context.save()
} catch {
print("Storing data Failed")
}
fetchData()
}
func fetchData()
{
print("Fetching Data..")
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
let userName = data.value(forKey: "username") as! String
let age = data.value(forKey: "age") as! String
print("User Name is : "+userName+" and Age is : "+age)
}
} catch {
print("Fetching data Failed")
}
}
}
Step 5. Run on Device and see log for core data results
Saving data:
var person = NSEntityDescription.insertNewObjectForEntityForName("Person",
inManagedObjectContext: self.managedObjectContext!) as Person
person.name = "Mary"
person.age = Float(arc4random() % 100)
var error : NSError? = nil
if !self.managedObjectContext!.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
Loading data:
var error: NSError? = nil
var fReq: NSFetchRequest = NSFetchRequest(entityName: "Frases")
fReq.predicate = NSPredicate(format: "id contains[c] %@", String(day))
var sorter: NSSortDescriptor = NSSortDescriptor(key: "id" , ascending: false)
fReq.sortDescriptors = [sorter]
fReq.returnsObjectsAsFaults = false
let result : [AnyObject] = self.managedObjectContext!.executeFetchRequest(fReq, error:&error)!