Day 57 of 100 Days of SwiftUI

sanmiade

Oluwasanmi Aderibigbe

Posted on May 10, 2021

Day 57 of 100 Days of SwiftUI

I just completed day 57 of 100 days of SwiftUI. Today I learnt more about CoreData. I learnt how to create CoreData models without optional, how to ensure the uniqueness of your models using constraints and the conditional saving of NSNSManagedObjectContext.

By default, properties of models created by CoreData are optional. To make them non-optional, you have to opt out of code-gen. You can do this by selecting the code-gen manual/none option and creating an NSManagedObject subclass.
Alt Text
This will create to two classes for you. Person+CoreDataProperties.swift and Person+CoreDataClass.swift (Person is the name of my model)

extension Person {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Person> {
        return NSFetchRequest<Person>(entityName: "Person")
    }

    @NSManaged public var name: String?

    public var wrappedName: String {
        name ?? "Unknown Name"
    }
}

extension Person : Identifiable {

}
Enter fullscreen mode Exit fullscreen mode

The code above is an NSManagedObject subclass. It has an optional property called name. In order to make that property non-optional, we simply created a computed property called wrappedName.

In order to make your data unique, all you have to do is add this line of code to the willConnectTo method in the SceneDelegate.swift directly below the code that starts with let context

context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sanmiade
Oluwasanmi Aderibigbe

Posted on May 10, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Go from one screen to another in SwiftUI
100daysofcode Go from one screen to another in SwiftUI

March 27, 2023

model show on click in swiftUI
100daysofcode model show on click in swiftUI

March 24, 2023

confirmationDialog() in swiftUI
100daysofcode confirmationDialog() in swiftUI

March 24, 2023

Item delete & Move in SwiftUI
100daysofcode Item delete & Move in SwiftUI

March 24, 2023