DEV Community

Anis Ali Khan
Anis Ali Khan

Posted on

Tutorial 32: Core Data Basics - Storing Structured Data Locally πŸš€

Featuring: The Legendary Fart Button App πŸ’¨


Welcome, brave coder! πŸ§™β€β™‚οΈβœ¨ Today we're going to embark on an epic quest: learning Core Data β€” Apple's magical framework for storing structured data locally on iOS devices.

And yes, we're doing it with the world-changing Fart Button App. Because learning is better with farts. πŸ’₯


πŸ“š What You'll Learn

  • What is Core Data?
  • Setting up Core Data in a project
  • Creating a simple Fart entity
  • Saving, fetching, and deleting data
  • Building a simple UI to interact with it

πŸ€” What Is Core Data?

Core Data is Apple's solution for managing an object graph β€” basically, storing and retrieving your app's data 🧠.

Think of it like:

  • User taps a button ➑️ Save a fart to the database πŸ’¨
  • User opens the app again ➑️ Fart history still there πŸ“œ

Without Core Data, your app would forget every beautiful fart pressed. 😒


πŸ›  Setting Up Core Data

  1. Create a new Xcode project.
    • Template: App
    • Make sure you check "Use Core Data" βœ…
  2. Xcode auto-generates some Core Data boilerplate!
    • Persistence.swift
    • Model.xcdatamodeld

This is where the magic happens! πŸͺ„


πŸ’¨ Creating the Fart Entity

In Model.xcdatamodeld:

  1. Click the + ➑️ Add Entity ➑️ Name it Fart.
  2. Add an attribute:
    • Name: soundName
    • Type: String
  3. Add another attribute (optional):
    • Name: timestamp
    • Type: Date

Now you have a database table ready to store farts. Historic. 🎺


πŸ–₯ Let's Build the Fart Button UI

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Fart.timestamp, ascending: true)],
        animation: .default)
    private var farts: FetchedResults<Fart>

    var body: some View {
        VStack(spacing: 20) {
            Button(action: addFart) {
                Text("πŸ’¨ Fart Button πŸ’¨")
                    .font(.largeTitle)
                    .padding()
                    .background(Color.green)
                    .cornerRadius(12)
                    .foregroundColor(.white)
            }

            List {
                ForEach(farts) { fart in
                    Text(fart.soundName ?? "Unknown Fart")
                }
                .onDelete(perform: deleteFarts)
            }
        }
        .padding()
    }

    private func addFart() {
        withAnimation {
            let newFart = Fart(context: viewContext)
            newFart.soundName = "ClassicFart.mp3"
            newFart.timestamp = Date()

            do {
                try viewContext.save()
            } catch {
                print("😱 Failed to save fart: \(error.localizedDescription)")
            }
        }
    }

    private func deleteFarts(offsets: IndexSet) {
        withAnimation {
            offsets.map { farts[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                print("😱 Failed to delete fart: \(error.localizedDescription)")
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Boom. You now have a functional fart database. πŸŽ‰


🧠 How It All Works

  • @Environment(\.managedObjectContext) gives access to Core Data's magical save powers.
  • @FetchRequest automatically listens to changes and updates the UI.
  • addFart() creates a new Fart entity and saves it.
  • deleteFarts() removes farts from history. (Pour one out. 🍻)

🧹 Pro Tips for Core Data

  • Always save after creating, updating, or deleting.
  • Use @FetchRequest smartly to drive your UI updates automatically.
  • Think about relationships (e.g., maybe a Fart Category later...πŸ’­).
  • Don't forget to handle errors gracefully.

🎯 Final Thoughts

You just built a Core Data powered app. And not just any app β€” a Fart Button that saves history for future generations to admire. πŸ†

Next steps:

  • Add custom fart sounds
  • Add categories ("Loud", "Silent", "Squeaky") 🧩
  • Build a Leaderboard ("Most Farts in a Day") πŸ₯‡

The possibilities are endless... and endlessly hilarious.


Keep coding and stay classy! πŸ’¨πŸ‘‘

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video β†’

Top comments (0)

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one serverβ€”search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

πŸ‘‹ Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay