DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on

3 2

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

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay