UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

CoreData Optionals: Creating NSManagedObject subclasses

Forums > 100 Days of SwiftUI

In Creating NSManagedObject subclasses, Paul suggests subclassing in order to set default values. Could the same thing be accomplished simply by unchecking the Optional checkbox and defining a default value in the inspector for each item in the entity? Why go the subclass route?

2      

No, unfortunately, this doesn't work. Even if you uncheck the optional box the values are still optional. Sounds crazy? Actually, it isn't. The checkbox in Xcode just makes sure that when saving the record a value is given. That doesn't mean the value of the NSManagendObject subclass is checked. F.e. you could leave the Optional checkbox checked but still provide a default value.

If you want to remove the check completely you have to set the classes to manual. Then you can create the classes via Xcode menu and two files are created. One class and one extension of the class. The extension contains all attributes. This is because, if you change attributes and recreate the files, only the extension is recreated. If you remove the ? from the attributes in the extension then you won't have to check for optional again. But then it's your responsibility to provide a value at any given time.

I would go with Paul's solution.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.