Core Data With Swift 4.0 Tutorial

Core Data - Core Data is a framework that you use to manage the data model layer objects or instance Context in your application. It provides generalized and automated data stores solutions to common tasks associated with object life cycle and object graph management, including persistence.

Completely Tutorial for Swift 4 and iOS 11.

Gating Start Goto Xcode and create New iOS Project on single view. Project Name CoreDataSwift
or Checked Use Core Data

Use Core Data

On click Main.Storyboard in Interface builder click on project navigation Editor - Embed In - Navigation controller.

Navigation Controller



Then After click on Navigation ViewController and next Drag TableView in to ViewController.

Drag TableView


Make TableView viewcontroller Outlet Delegate, DataSource and import CoreData

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
  
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Next IBOutlet Property TableView UITableView is tableView and register tableView Nib viewDidLoad


     @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Thie List"
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        // Do any additional setup after loading the view, typically from a nib.
    }

Now we will pick up function UITableViewDataSource

// UITableViewDataSource

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let person = people[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = person.value(forKeyPath: "name") as? String
            return cell

        }


Start build and Run Project CoreDataSwift app ViewController look like Simulator 

able View Simulator

Now Use CoreData Modeling 

Xcode automatically create data model



Create New Entity name "Person" and create attributes "name" type string

Now drag a Bar Button Item Add viewController Navigation bar

BarButtonItem

Now Create a addName function on to Add BarButtonItem

@IBAction func addName(_ sender: Any) {
        
        let alert = UIAlertController(title: "New Name",message: "Add a new name", preferredStyle: .alert)
        
        let saveAction = UIAlertAction(title: "Save", style: .default) {
            [unowned self] action in
            
            guard let textField = alert.textFields?.first, let nameToSave = textField.text else {
                    return
            }
            
            self.save(name: nameToSave)
            self.tableView.reloadData()
        }
        
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .default)
        alert.addTextField()
        
        alert.addAction(saveAction)
        alert.addAction(cancelAction)
        
        present(alert, animated: true)
        
    }

Saving Core Data


Import CoreData

Now Create two var name, people mutable array 

import UIKit

import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var names: [String] = []
    var people: [NSManagedObject] = []
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Thie List"
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        // Do any additional setup after loading the view, typically from a nib.
    }

Create  save func to manage saving core data

func save(name: String) {
        
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                return
        }
        
        let managedContext = appDelegate.persistentContainer.viewContext
        

        let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
        
        let person = NSManagedObject(entity: entity, insertInto: managedContext)
        

        person.setValue(name, forKeyPath: "name")
        
     
        do {
            try managedContext.save()
            people.append(person)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }

Full Core data ViewController File


//
//  ViewController.swift
//  CoreDataSwift
//
//  Created by Praveen Raman on 12/28/17.
//  Copyright © 2017 Apple. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var names: [String] = []
    var people: [NSManagedObject] = []
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Thie List"
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        // Do any additional setup after loading the view, typically from a nib.
    }
    // UITableViewDataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let person = people[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = person.value(forKeyPath: "name") as? String
            return cell
        }
    
    @IBAction func addName(_ sender: Any) {
        
        let alert = UIAlertController(title: "New Name",message: "Add a new name", preferredStyle: .alert)
        
        let saveAction = UIAlertAction(title: "Save", style: .default) {
            [unowned self] action in
            
            guard let textField = alert.textFields?.first, let nameToSave = textField.text else {
                    return
            }
            
            self.save(name: nameToSave)
            self.tableView.reloadData()
        }
        
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .default)
        alert.addTextField()
        
        alert.addAction(saveAction)
        alert.addAction(cancelAction)
        
        present(alert, animated: true)
        
    }
    
    func save(name: String) {
        
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                return
        }
        
        // 1
        let managedContext = appDelegate.persistentContainer.viewContext
        
        // 2
        let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
        
        let person = NSManagedObject(entity: entity, insertInto: managedContext)
        
        // 3
        person.setValue(name, forKeyPath: "name")
        
        // 4
        do {
            try managedContext.save()
            people.append(person)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

Output:-


Popular posts from this blog

ASO Off-Page Activities - Free Submission Site Promote Mobile App

Mobile Apps Optimizing High Rank in App Store’s Android or iphone - ASO

How Create Animated Circle Progress Bar iOS 11 Swift 4

Complete Increasing Search Ranking mobile Application