Question

I'm new to Core Data, and am not sure how to reconcile the need to inherit from NSManagedObject with the fact that my model is a Swift struct composed of structs. I chose to make my a model value type so that it would be simple to push and pop it onto an undo stack. But since a value type can't inherit, I'm unsure as to where to go next in order to save my model to the database. Should I turn my model into a class and use UndoManager instead? What might be some other possible approaches?

Was it helpful?

Solution

You have some options:

1 - Convert them to class. So you can inherit from NSManagedObject and do the rest like the tutorials you usually find in internet.

2 - Make a rapper around any struct you want to store in core data. For example if you have some struct like this:

struct Student {
    let name: String
}

it will be wrapped like this:

class ManagedStudent: NSManagedObject {

    @NSManaged var name: String

    var student: Student {
       get {
            return Student(name: self.name)
       }
       set {
            self.name = newValue.name
       }
     }
}

but be careful about differences of a value type and a reference type and a nested mixed type. You can even make some of the implementation more private to make extra codes more transparent.

3 - You can make your structs conform to NSCoding and encode it directly to the database. but unfortunately as it seems, you can not perform well efficient queries on them.

4 - Use other libraries instead of CoreData. There are some libraries out there supporting structs out of the box and some of them are written on top of the CoreData.

5 - Don't use database at all! I don't know your use case but if there is no relations between objects, You usually don't need a data base at all. A simple file system can do all stuff.

Oh and one more thing, If you are new to CoreData and you just want to play with it until you learn it, stick to the first option. Once you get used to it, examine other options as well.

Good luck.

Licensed under: CC-BY-SA with attribution
scroll top