Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store my own enum as an attribute in CoreData

Tags:

ios

core-data

I defined a global enum named MyEnum:

enum MyEnum: Int{
    case year = 100, month, week, day
}

Purpose is to stored this enum as an attribute of my entity(I declare this enum attribute as transformable in xcdatamodel file):

enter image description here

After Creating NSManagedObject Subclass, In +CoreDataProperties.swift, I tried to changed the

@NSManaged public var myEnum: NSObject

to

@NSManaged public var myEnum: MyEnum

But when performing saveContext(), error still occurred. I just begin to learn and have no way about how to do next

so what extra work should I do to stored my enum as an attribute for my entity?

Please use swift, thanks for any help

like image 370
Hao Avatar asked Dec 24 '22 11:12

Hao


1 Answers

We generally store enumerations as strings or as integers into database. It really depends on the case which to use but consider you have something like

@NSManaged public var myEnumAsInteger: Int

Then to save it all you do is:

myObject.myEnumAsInteger = enumValue.rawValue

and to read it:

enumValue = MyEnum(rawValue: myObject.myEnumAsInteger)

Or you can just create another property and override getter, setter as so:

@NSManaged public var myEnumAsInteger: Int

var myEnum: MyEnum {
    set {
        self.myEnumAsInteger = newValue.rawValue
    }
    get {
        return MyEnum(rawValue: self.myEnumAsInteger) ?? .year // Or whatever the default is
    }

}
like image 102
Matic Oblak Avatar answered Jan 05 '23 08:01

Matic Oblak