Core Data can seem intimidating, but it’s incredibly powerful for certain use cases. Let’s build a habit tracker to see it in action.

Why Core Data?

For apps with complex data relationships and offline-first requirements, Core Data shines. Here’s a practical example.

Data Model

// Habit entity with streaks
@objc(Habit)
public class Habit: NSManagedObject {
    @NSManaged public var id: UUID
    @NSManaged public var name: String
    @NSManaged public var createdAt: Date
    @NSManaged public var completions: NSSet?
    
    var currentStreak: Int {
        // Calculate streak from completions
    }
}

Tracking Completions

func markComplete(for habit: Habit, on date: Date) {
    let context = persistentContainer.viewContext
    let completion = Completion(context: context)
    completion.id = UUID()
    completion.date = date
    completion.habit = habit
    
    do {
        try context.save()
        NotificationCenter.default.post(
            name: .habitCompleted,
            object: nil
        )
    } catch {
        print("Failed to save: \(error)")
    }
}

The Streak Algorithm

func calculateStreak(for habit: Habit) -> Int {
    let calendar = Calendar.current
    var streak = 0
    var checkDate = Date()
    
    while true {
        let hasCompletion = habit.completions?.contains { completion in
            calendar.isDate(completion.date!, inSameDayAs: checkDate)
        } ?? false
        
        if hasCompletion {
            streak += 1
            checkDate = calendar.date(byAdding: .day, value: -1, to: checkDate)!
        } else {
            break
        }
    }
    
    return streak
}

Visual Streak Display

Core Data’s integration with SwiftUI makes building data-driven apps more straightforward than ever.