我正在制作一个绘图应用程序,允许用户保存和重新打开绘图,因此我需要使用 CoreData。其中一项功能是能够更改路径颜色。我需要在每个 UIBezierPath 中存储一种颜色,以便在绘制时以正确的颜色描画它。因此我对 UIBezierPath 进行了子类化:
class colorPath: UIBezierPath {
var pathStrokeColor: UIColor?
}
然后我在draw(_ rect:)函数中绘制这样的路径:
for path in paths{
path.pathStrokeColor?.setStroke()
path.stroke()
}
这工作正常,直到我关闭应用程序并重新打开它。 pathStrokeColor 只有一个 nil 值,并以默认颜色 - 黑色绘制。
路径数组的数组像这样保存在Core Data实体JFile中。 “thearray”是可转换类型,因此我将 colorPath 转换为 NSObject:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let afile = JFile(context: context)
afile.thearray = arrayOfPages as NSObject
(UIApplication.shared.delegate as! AppDelegate).saveContext()
路径数组的数组是这样检索的。我必须将 NSObject 数组转换回 colorPath:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let jfiles = try context.fetch(JFile.fetchRequest())
let filez = files as! [JFile]
if filez.count>0{
arrayOfPages = filez[myindex].thearray as! [[colorPath]]
}
所以我假设我错误地子类化了 UIBezierPath,因为与 Core Data 一起使用的唯一变量是我自己创建的变量——pathStrokeColor。我的语法错误吗?这与 pathStrokeColor 是可选的有关吗?是因为我无法将我的子类分类为 NSObject 吗?我该如何解决这个问题?
最佳答案
您无法将任何对象保存到核心数据中。它必须是数字、日期、字符串或数据。通常,如果您想存储除此之外的其他内容,请首先将其转换为数据以存储它,并在您想要读取它时从数据中解码它。根据您共享的代码,似乎没有任何地方发生这种情况。
当属性可转换时,它允许您将符合 NSCoding
的任何对象存储到 core-data 中。但这不是魔法。符合 NSCoding
的对象实现 init?(coder aDecoder: NSCoder)
和 encode(with aCoder: NSCoder)
,它们将对象与对象进行相互转换数据。
UIBezierPath
已经符合 NSCoding
,因此技术上您的子类也符合。但是您的子类没有存储其额外的属性。您还必须在子类中实现编码:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if let color = aDecoder.decodeObject(forKey: "pathStrokeColor") as? UIColor{
pathStrokeColor = color
}
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
if let color = pathStrokeColor{
aCoder.encode(color, forKey: "pathStrokeColor")
}
}
关于ios - 自定义子类中的变量不会保存/不会从核心数据加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45782458/