Hi guys, today we will learn about how to create a core data app in swift
Before starting it we need to know what is Core Data.
Core Data
Core Data is a set of Tools (referred to as a Framework) that will allow you to save (referred to as Persist) and Retrieve the data in your iOS application to the iOS Device that your application is running on.
It does this by implementing something called ORM (Object Relational Mapping). This basically just means that Core Data will interact with your Swift Objects without you having to worry about the code that is handled. Core Data will handle how the data from your Swift Objects is stored and retrieved from the persisted data stores like relational databases from SQLite or flat files.
Creating a Core Data App in Swift
1.) First, let’s create a new project and let’s select “Use Core Data”. Although you can add that framework for your existing project, it’s easier to add it from that place as everything will be wired up already for you.
Once the project is created, you will see a file like CoreDataExample.xcdatamodeld added.
When you click it, you will see a tool that allows you to configure entities which represents data models. You can define few things for each entity there but for us Attributes and Relationships will be most important.
2.) Let’s add a new entity called CoreData (to change it’s name once you’ve clicked Add Entity button, click the name of a newly added entity on top twice and type in your name).
Now, let’s add a few attributes that will define a schema of our new entity : name — String, id — Integer 64
3.) Create a new object called managed object model,, persist in the storage and read it after that.
Note: CoreData uses a SQLite database as the persistent store.
- Open ViewController.swift,
- Import CoreData module,
1import CoreData - Create a managed object model ,
1 2 3 4 5 |
var coreData : [NSManagedObject] = [] @IBOutlet weak var coreDataTableView: UITableView! var managedContext: NSManagedObjectContext = { (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext }() |
- Fetch the data from the record
12345678let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CoreData")do {coreData = try (managedContext.fetch(fetchRequest))coreDataTableView.reloadData()}catch let error as NSError {print("Could not fetch. \(error), \(error.userInfo)")}
4.) Now arrange the persist data in UITableView :
1 2 3 4 5 6 7 8 9 10 11 |
extension ViewController : UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return coreData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = coreData[indexPath.row].value(forKeyPath: "name") as? String return cell } } |
5.) To save data in your persistent store into the managed object context, you have to save it. Open ViewController.swift and add the following below addData(_ sender: Any):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
@IBAction func addData(_ sender: Any) { let alert = UIAlertController(title: "Add", message: nil, preferredStyle: .alert) alert.addTextField { (textField) in textField.keyboardType = .alphabet } let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } let count = self.coreData.count self.save(name: nameToSave, id: Int64(count+1)) self.coreDataTableView.reloadData() } alert.addAction(saveAction) self.present(alert, animated: true, completion: nil) } public func save(name: String, id: Int64 ) { let newItem = CoreData(context: managedContext) newItem.name = name newItem.id = id coreData.append(newItem) managedContext.performAndWait { do { try managedContext.save() } catch let error as NSError { print("could not save, managedobject \(error), \(error.userInfo)") } } } |
Key Points
- It provides on–disk persistence, which means your data will be accessible even after terminating your app or shutting down your device.
- Xcode comes with a powerful Data Model editor, which you can use to create your managed object model.
- A managed object model is made up of entities, attributes and relationships
- An entity is a class definition on it.
- An attribute is a piece of information attached to an entity.
- An
NSManagedObject
is a run-time representation of a Core Data entity. You can read and write to its attributes using Key-Value Coding. - You need an
NSManagedObjectContext
tosave()
orfetch(_:)
data to and from Core Data.
Conclusion
So please follow the above step and and if you have any issue or suggestion you can leave your query/suggestion in the comment section I will try to solve that.