bhylu.com

Advertisements

Swift Core Data

Learn the model, context and save boundary with an intentionally in-memory store. Requires Mac/Xcode; this Apple-only source was not SDK-compiled or run here.

How it works

Core Data manages an object graph and persistent-store coordination; it is not simply a Codable file. This source builds a small model programmatically and uses an in-memory store, so it needs no hidden xcdatamodeld asset. A disk store, migration, background contexts and durable recovery require additional work and tests.

Apple-only setup and review status

Create a separate iOS SwiftUI App learning project in a suitable Xcode version, choose an appropriate simulator/device and replace the generated app/view Swift source with this complete file. Keep one @main entry point. Widget and App Clip lessons explicitly require their own extension/clip targets instead; capability, purpose-string, entitlement and account steps in the lesson must be completed separately. No Xcode project, signing certificate, account or service was provisioned here.

Bhylu has no Swift browser runner. The JavaScript/Python editors do not run these sources; Apache, PHP and MySQL are not required. Downloads are source text, never executable teaching endpoints.

Download the complete core-data.swift · Download all source files with hash checks

For the optional collection, save download-examples.mjs in a new folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/swift/. It refuses an existing bhylu-swift-examples folder and installs or executes no Swift automatically. Apple-only files remain separate Xcode learning examples, not a portable Swift package target.

Example

core-data.swift

// Apple-only learning file: iOS 17+ target with a suitable Xcode SDK.
// Not compiled or run in this Windows/Linux review.
import SwiftUI
import CoreData

@objc(WorkshopNote) final class WorkshopNote: NSManagedObject { @NSManaged var label: String }
@MainActor final class MemoryStore {
    static let shared = MemoryStore()
    let container: NSPersistentContainer
    init() {
        let attribute = NSAttributeDescription()
        attribute.name = "label"; attribute.attributeType = .stringAttributeType; attribute.isOptional = false
        let entity = NSEntityDescription()
        entity.name = "WorkshopNote"; entity.managedObjectClassName = NSStringFromClass(WorkshopNote.self)
        entity.properties = [attribute]
        let model = NSManagedObjectModel(); model.entities = [entity]
        container = NSPersistentContainer(name: "WorkshopMemory", managedObjectModel: model)
        let store = NSPersistentStoreDescription(); store.type = NSInMemoryStoreType
        store.shouldAddStoreAsynchronously = false
        container.persistentStoreDescriptions = [store]
        container.loadPersistentStores { _, error in precondition(error == nil, "Memory store failed") }
    }
}

struct DemoView: View {
    @Environment(\.managedObjectContext) private var context
    @FetchRequest(sortDescriptors: []) private var notes: FetchedResults<WorkshopNote>
    @State private var notice = "In-memory notes only"
    var body: some View {
        VStack {
            List(notes, id: \.objectID) { Text($0.label) }
            Button("Add draft note") {
                let note = WorkshopNote(context: context)
                note.label = "Check glaze sample"
                do { try context.save(); notice = "Saved in this process only" }
                catch { context.rollback(); notice = "Save failed" }
            }
            Text(notice)
        }.environment(\.managedObjectContext, MemoryStore.shared.container.viewContext)
    }
}

@main
struct WorkshopDemoApp: App {
    var body: some Scene { WindowGroup { DemoView().environment(\.managedObjectContext, MemoryStore.shared.container.viewContext) } }
}

Expected behaviour and manual checks

Manual Xcode check: build the app, add notes, exercise a save failure in a controlled test and relaunch. The memory store is deliberately empty after relaunch; no durable-save claim is made. Core Data compilation and execution were not available here.

The managed object’s identity comes from objectID. The model declares the label field and the context owns changes. The scene must inject the context above the fetching view; the final source’s root wrapper does that explicitly.

Primary references: The Swift Programming Language and Apple framework documentation. Use the selected platform’s current requirements. Fictional workshop examples do not establish production safety or deployment approval.

Advertisements