Work with Core Data in Swift Language

Lets take a brief idea about how to use core data with swift language.

Create a new project by check on Use Core Data.

Core Data Project Setting
Core Data Project Setting

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 :

Core Data Model
Core Data Model

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.

import CoreData

Lets Save the Data in the Entity

We will get the NSManagedObjectContext reference from the AppDelegate.

// 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

// 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

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 🙂

  • can u add query Insert, Update and Delete functionality in Core Data.

  • Muhammad Rizwan Mughal

    can u do make an article with example of core data with relationships? simply in “to many relationship”