我正在制作一个允许用户保存和重新打开图纸的绘图应用程序,因此我需要使用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吗?我该如何解决这个问题?
答案 0 :(得分:0)
您无法将任何对象保存到核心数据中。它必须是数字,日期,字符串或数据。通常,如果您要存储除此之外的其他内容,则首先将其转换为数据以存储它,并在您想要读取数据时从数据中解码。根据您共享的代码,似乎没有任何地方发生这种情况。
当属性可转换时,它允许您将符合NSCoding
的任何对象存储到核心数据中。但这不是魔术。符合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")
}
}