Swift CRUD using Local Database


To use a local database in Swift, you can use a framework such as Core Data or Realm. In this example, we will use Core Data to create a simple to-do list application that allows users to create, read, update, and delete tasks.

  1. Create a new Xcode project with the “Core Data” option selected.
  2. Open the “Data Model” file and create a new entity called “Task” with attributes “title” (String) and “completed” (Boolean).
  3. Generate a NSManagedObject subclass for the “Task” entity by selecting “Editor” -> “Create NSManagedObject Subclass”.
  4. Create a new view controller with a UITableView and a UIButton. In the view controller, add an IBOutlet for the UITableView and an IBAction for the UIButton.
  5. In the view controller, create an instance of NSManagedObjectContext and a variable to store an array of tasks.
import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var tasks: [Task] = []
    
    lazy var managedObjectContext: NSManagedObjectContext = {
        return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        fetchTasks()
    }
    
    @IBAction func addTaskButtonPressed(_ sender: UIButton) {
        // TODO: Implement adding a new task
    }
    
    func fetchTasks() {
        let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
        
        do {
            tasks = try managedObjectContext.fetch(fetchRequest)
            tableView.reloadData()
        } catch {
            print("Error fetching tasks: \(error)")
        }
    }
}

Leave a Reply