Search code examples
swiftcore-dataswiftui

NSManagedObjectContext Subclasses


I'm learning how to use Core Data and I am really close to build a simple project using this module but I don't clearly understand what are MOC Subclasses for? One time I heard that [NSManagedObject Name]+CoreDataClass.swift can be modified with some methods. So I have 3 questions about them:

  • Can I use CoreDataClass as ViewModel for data?
  • What are those files really for?
  • Why my simple function doesn't save (it's of course part of Point+CoreDataClass.swift file) enter image description here

Solution

  • Can I use CoreDataClass as ViewModel for data

    Technically this is the standard way of doing things, except there is a middle concept in between both the CoreDataClass and the ViewModel and that is @FetchRequest. Now personally I have always seen CoreData (@FetchRequest) used directly on the view because, well there is no need to abstract it further than that.

    What are those files really for?

    Back in the GUI for CoreDataEntity there is an option for ClassDefinition or ClassGen.. these files are the files that swift automatically makes for you. Now depending on whether or not you see them will depend on what you select for ClassDefinition.

    This question is directly related to your first question because in essence this files serves as the view model. Because in these files you will have your properties

    Example:

    @NSManaged var name: String

    Why my simple function doesn't save (it's of course part of Point+CoreDataClass.swift file)

    You were so close. And that is that you failed to define a context You need to first say:

    let myData = YourEntityName(context: context)
    

    then say:

    myData.pointName = name
    

    then

    context.save()