Home > Software design >  How to set default value in core data array ? How to override the default value ? How to customize c
How to set default value in core data array ? How to override the default value ? How to customize c

Time:03-01

I'm trying to make a Storage Expiration Notification APP.

I create a class called Product, here are the properties.

@NSManaged public var productName: String?
@NSManaged public var quantity: String?
@NSManaged public var category = ["", "Food", "Daily", "Makeup"]
@NSManaged public var chooseCategory: Int16
@NSManaged public var purchaseDate: String?
@NSManaged public var expiredDate: String?
@NSManaged public var productID: String?

But there's an Error showed that @NSManaged property cannot have an initial value

Hence, I only can move the Category array(use picker controller to choose the values) to ViewContorller.swift. But I want to create a Customize Category array that users can change the value. For instance, the default category is ["Food", "Daily", "Makeup"], users can change the value to ["Drink", "Wine", "Battery"]. Should I use archiving, or create a new class? I have no idea how to implement it.

CodePudding user response:

The Core Data way to do this is by overriding awakeFromInsert. That function is inherited from NSManagedObject and is called once when the object is first inserted into a managed object context. For this case it would look something like

func awakeFromInsert() {
    category = ["", "Food", "Daily", "Makeup"]
}

It doesn't work in exactly the same way as a Swift initial value but it has the same effect since it happens when you create a new instance.

CodePudding user response:

A @NSManaged property cannot even be an array.

A lightweight Swift solution is a JSON string attribute and a computed property for the conversion.

@NSManaged public var category : String

and

var categoryArray : [String] {
    get { (try? JSONDecoder().decode([String].self, from: Data(category.utf8))) ?? [] }
    set {
        let data = try! JSONEncoder().encode(newValue)
        category = String(data: data, encoding: .utf8)!
    }
}

Set the default value

"[\"\",\"Food\",\"Daily\",\"Makeup\"]

either in awakeFromInsert or in Interface Builder in the model

  • Related