如何在核心数据数组中设置默认值?如何覆盖默认值?如何自定义分类?
我正在尝试制作一个存储过期通知应用程序。
我创建了一个名为 Product 的类,以下是属性。
@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?
但有一个错误表明 @NSManaged 属性不能有初始值
因此,我只能将 Category 数组(使用选择器控制器选择值)移动到 ViewContorller.swift
。但我想创建一个自定义类别数组,用户可以更改该值。例如,默认类别是["Food", "Daily", "Makeup"]
,用户可以将值更改为["Drink", "Wine", "Battery"]
。我应该使用存档还是创建一个新类?我不知道如何实施它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
错误是正确的,@NSManaged 属性不能有初始值。
轻量级 Swift 解决方案是 JSON 字符串属性和用于转换的计算属性。
并
设置默认值
在模型的
awakeFromInsert
或 Interface Builder 中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 modelCore Data 执行此操作的方法是重写 awakeFromInsert。该函数继承自 NSManagedObject,并在对象首次插入托管对象上下文时调用一次。对于这种情况,它看起来像
它的工作方式与 Swift 初始值不完全相同,但它具有相同的效果,因为它是在您创建新实例时发生的。
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.