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
The Core Data way to do this is by overriding
awakeFromInsert
. That function is inherited fromNSManagedObject
and is called once when the object is first inserted into a managed object context. For this case it would look something likeIt 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.
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.
and
Set the default value
either in
awakeFromInsert
or in Interface Builder in the model