Lets take a brief idea about how to use core data with swift language.
Create a new project by check on Use Core Data.
It will create the basic methods of core data in to the AppDelegate.swift
There is core data model called {YOUR-PROJECT.xcdatamodeld} will be there with the project.
It will be look like as follows :
I have created one entity called “Devices”. You can see in the above screenshot.
Import the Core Data framework
For the functionalities of core data we have to import the core data framework.
1 |
import CoreData |
Lets Save the Data in the Entity
We will get the NSManagedObjectContext reference from the AppDelegate.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// SAVE DATA let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedObjectContext = delegate.managedObjectContext let entity = NSEntityDescription.entityForName("Devices", inManagedObjectContext: managedObjectContext) let managedObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext) managedObject.setValue("iPhone \(devices.count + 1)", forKey: "name") managedObject.setValue("Apple", forKey: "company") do { try managedObjectContext.save() } catch let error as NSError { print(error) } |
NSEntityDescription is used for find the Entity.
NSManagedObject will create new object in the Entity.
save() method is used for save the context.
Get all Data from Entity and Fill the table
1 2 3 4 5 6 7 8 9 10 11 |
// GET DATA let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Devices") do { let results = try managedContext.executeFetchRequest(fetchRequest) devices = results as! [NSManagedObject] self.tableView.reloadData() } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } |
NSFetchRequest is used to fetch the data from the Entity.
Sample Code
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import UIKit import CoreData class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var devices = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() //Document Path let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] print(documentsPath) getData() // Do any additional setup after loading the view, typically from a nib. } func getData(){ // GET DATA let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Devices") do { let results = try managedContext.executeFetchRequest(fetchRequest) devices = results as! [NSManagedObject] self.tableView.reloadData() } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } @IBAction func btnSaveDataPressed(sender: AnyObject) { saveData() getData() } func saveData(){ // SAVE DATA let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedObjectContext = delegate.managedObjectContext let entity = NSEntityDescription.entityForName("Devices", inManagedObjectContext: managedObjectContext) let managedObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext) managedObject.setValue("iPhone \(devices.count + 1)", forKey: "name") managedObject.setValue("Apple", forKey: "company") do { try managedObjectContext.save() } catch let error as NSError { print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let aCell = tableView.dequeueReusableCellWithIdentifier("coreCell", forIndexPath: indexPath) let person = devices[indexPath.row] aCell.textLabel?.text = person.valueForKey("name") as? String return aCell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return devices.count } } |
In the next tutorials I will try to add about the Insert, Update and Delete functionality with the use of Core Data.
Happy Coding 🙂