skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. The error is right, an @NSManaged property cannot have an initial value.

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search