FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

Core Data With Single Set Of Data

Forums > macOS

Hi I'm new to core data so appreciate I may be missing the obvious but....

I have created an entity (Licence) which has 4 attributes (licenceID:UUID, startDate:String, endDate:String, licenceName:String).

I've been able to create a fetch request using the below, as well as display records in a list, add records, delete records.

struct ContentView: View { @FetchRequest(entity: Licence.entity(),sortDescriptors: []) var currLicence: FetchedResults<Licence> @Environment(.managedObjectContext) var moc

var body: some View { etc etc

What I'm struggling with is... Due to the way my app works there will only ever be one set of data for the entity. How can I refer to this single record within my view??

EG1 - Rather than using a list I'd prefer to have a simple text view. Using something like...

Text("Start Date:- (currLicence.startDate)")

EG2 - Be able to refer to an attribute. Using something like...

if currLicence.licenceName == "Dave" { etc etc

I appreciate that the nature of the fetchRequest is to return sets of data but is there a way to filter to one record eg .first?? Apologies if I'm missing the obvious - any pointers??

   

You are looking for NSPredicate here is the iOS SwiftUI version, but you can look into how to implement it in your app.

https://www.hackingwithswift.com/books/ios-swiftui/filtering-fetchrequest-using-nspredicate

However, if you are only ever using a single entity then Core Data is not really useful here. If the license needs to be kept somewhere safe, you might want to look into using Keychain Access. If it's not necessary to store securely, then User Defaults would make more sense.

   

Thanks Marcus Unfortunately I need to store the data within the app. Predicate will work well to retreive the one instance of data. I was hoping that there would be an easy way of referencing the attributes of the single item. Will keep trying...

   

I agree with Marcus.

If you are only going to have a single entity and/or a single instance of that entity (or even a single instance of multiple entities) you don't need CoreData. You don't mention how large this instrance of data is, but if it is license data, it is probably not that large.

I would suggest you simplify your life and use another option to persist the data. For example:

Using @AppStorage would look like this and is automatically persisted in the App bundle anytime any of the values change.

import SwiftUI

struct ContentView: View {

    @AppStorage("appLicenseID") var appLicenseID = "none"
    @AppStorage("appLicenseFirstName") var appLicenseFirstName =  "none"
    @AppStorage("appLicenseLastName") var appLicenseLastName =  "none"
    @AppStorage("appLicenseEmail") var appLicenseEmail =  "none"
    @AppStorage("appLicenseStartDate") var appLicenseStartDate = "none"
    @AppStorage("appLicenseEndDate") var appLicenseEndDate = "none"

    var body: some View {

        VStack {
            if appLicenseID == "none" {
                VStack {
                    Text("No License Information")

                    Button("Add License Data") {
                        appLicenseID = UUID().uuidString
                        appLicenseFirstName = "Tom"
                        appLicenseLastName = "Smith"
                        appLicenseEmail = "tom@smith.com"

                        let today = Date()
                        let formatter = DateFormatter()
                        formatter.dateStyle = .short
                        appLicenseStartDate = formatter.string(from: today)

                        var dateComponent = DateComponents()
                        dateComponent.year = 1

                        let licenseEndDate = Calendar.current.date(byAdding: dateComponent, to: today)

                        appLicenseEndDate = formatter.string(from: licenseEndDate!)
                    }
                }
                .frame(width: 150, height: 75)
            } else {
                Text(appLicenseID)
                Text(appLicenseStartDate)
                Text(appLicenseEndDate)
                Text(appLicenseFirstName)
                Text(appLicenseLastName)
                Text(appLicenseEmail)

                Button("Clear License") {
                    appLicenseID = "none"
                    appLicenseFirstName = "none"
                    appLicenseLastName = "none"
                    appLicenseEmail = "none"
                    appLicenseStartDate = "none"
                    appLicenseEndDate = "none"
                }
            }
        }
        .frame(width: 300, height: 300)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.