CRUD app

To create a CRUD (create, read, update, delete) application in Swift using UserDefaults, you can use the UserDefaults class to store and retrieve data, as well as the UIKit and Foundation classes to create the user interface and handle user interactions.

Here is an example of a simple CRUD application in Swift using UserDefaults:

import UIKit

class ViewController: UIViewController {
    // MARK: - Properties

    var items: [String] = []

    // MARK: - Outlets

    @IBOutlet weak var tableView: UITableView!

    // MARK: - Actions

    @IBAction func addButtonTapped(_ sender: Any) {
        let alert = UIAlertController(title: "Add Item", message: "Enter the name of the item you want to add:", preferredStyle: .alert)

        alert.addTextField { textField in
            textField.placeholder = "Item name"
        }

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { action in
            let textField = alert.textFields![0]
            self.items.append(textField.text!)
            self.save()
        }))

        present(alert, animated: true, completion: nil)
    }

    // MARK: - Helper Methods

    func load() {
        if let items = UserDefaults.standard.array(forKey: "items") as? [String] {
            self.items = items
        }
    }

    func save() {
        UserDefaults.standard.set(items, forKey: "items")
        tableView.reloadData()
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
        let item = items[indexPath.row]
        cell.textLabel?.text = item
        return cell
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            items.remove(at: indexPath.row)
            save()
        }
    }
}

In this example, the ViewController class contains an array of String values called items, which represents the items in the application. The addButtonTapped action is called when the user taps the "Add" button, and it displays an alert with a text field for the user to enter the name of the item they want to add.

Previous
Previous

Benefits of using NSObject in Swift

Next
Next

Defining Polymorphism in Swift