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

Default Core Data entity value with static var property?

Forums > SwiftUI

I have a score property on my Core Data Entity Student. So, when adding a newStudent object, its related one-to-one score property must have a value, different from nil, to be saved.

User can change that score value later on another views, but for object creation itself I do need a default value. And I can't find a working way to set a default one.

My Student class:

extension Student {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Student> {
        return NSFetchRequest<Student>(entityName: "Student")
    }
    //Another properties...
    @NSManaged public var evaluation: Score?
}

My Score class:

extension Score {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Score> {
        return NSFetchRequest<Score>(entityName: "Score")
    }
    //Another properties...
    @NSManaged public var depiction: String?
    @NSManaged public var student: Student?
}

I suposse I have to create any type of singleton, and static var not to be created-and-saved each time I add a student, but just to pass it to the ViewContext to be saved as a part of newStudent saving. I hope I have explained myself...

I'm trying to add something like this to my Students+CoreDataMethods:

extension Score {
    static var defaultScore: Score {
        self.defaultScore.depiction = "None"
    }
    ...
}

But it throws errors like "Function call causes an infinite recursion", and "Missing return in getter expected to return 'Score'"".

I don't find a correct approach to deal with it. Any ideas? Thanks!

1      

When you create a Core Data entity in the model editor, you can indicate a default value for each property.

For example:

default value in Core Data model editor

This will cause the depiction property to have a default value of "None" whenever a new Score is created.

1      

Thanks.

Yes: it gives the value "None" for "score" property when a new "Score" is created.

But what I need is giving this "None" value to Students's "score" property, when a "Student" is created, to this property:

student.score.depiction

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.