Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a Swift struct in Core Data on iOS?

At the moment I'm storing one of my classes as NSData in a plist and obviously that isn't a good way to do it.

So I'm trying to set up Core Data, but my class has Structs. This is what I have:

import Foundation
import CoreData

class Favourite: NSManagedObject {
    @NSManaged var origin: Stop

    struct Stop {
        var name: String;
        var id: String;
    }
}

But this is no good because it says:

Property cannot be marked as @NSManaged because its type cannot be represented in Objective-C

Furthermore, if this error did not occur, I don't know what I'd set it up as in my xcdatamodeld file.

I guess I could store the values in the struct and assign on initialisation of the object? Is this the most optimal/clean way?

like image 996
r_t Avatar asked Jun 17 '16 08:06

r_t


People also ask

How do I save a struct in Core Data?

There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class. The second step is to add a to-many relationship in the Core Data entity where you want to store the array.

What is transformable in Core Data?

When you declare a property as Transformable Core Data converts your custom data type into binary Data when it is saved to the persistent store and converts it back to your custom data type when fetched from the store. It does this through a value transformer.

What is struct iOS Swift?

In Swift, a struct is used to store variables of different data types. For example, Suppose we want to store the name and age of a person. We can create two variables: name and age and store value. However, suppose we want to store the same information of multiple people.


1 Answers

I will proceed like this :

import Foundation
import CoreData

    struct Stop {
       var name: String;
       var id: String;
    }

    class Favourite: NSManagedObject {

        @NSManaged var name: String
        @NSManaged var id: String

        var stop : Stop {
           get {
                return Stop(name: self.name, id: self.id)
            }
            set {
                self.name = newValue.name
                self.id = newValue.id
            }
         }
    }

Very interesting article, you should read: http://www.jessesquires.com/better-coredata-models-in-swift/

like image 82
Sahin Elidemir Avatar answered Sep 25 '22 04:09

Sahin Elidemir