我有一个使用领域数据库保存数据的应用程序,并且一切正常,但是我现在遇到的问题是我想将photo: Data
数组保存到数据库中,我尝试使用标准的swift数组格式,但是得到了构建时出错。下面是我的代码
class TodoListModel: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var photo: Data? = nil
@objc dynamic var createdDate: Date?
override static func primaryKey() -> String? {
return "id"
}
let parentCategory = LinkingObjects(fromType: CategoryModel.self, property: "items")
}
我现在如何将photo
制成数组
这是我创建列表的方式
func createTodoList(createdDate: Date, photo: Data) -> Void {
let todoList = TodoListModel()
todoList.createdDate = createdDate
todoList.photo = photo
TodoListFunctions.instance.addData(object: todoList)
}
更新模型
func updateTodoList(update: TodoListModel, createdDate: Date, photo: Array<Data>) -> Void {
update.createdDate = createdDate
update.photo.append(objectsIn: photo)
}
答案 0 :(得分:1)
要能够在Data
子类的单个属性中存储Object
类型的多个对象,您需要使用List
。
class TodoListModel: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var createdDate: Date?
let photos = List<Data>()
let parentCategory = LinkingObjects(fromType: CategoryModel.self, property: "items")
override static func primaryKey() -> String? {
return "id"
}
}
然后您可以创建一个TodoListModel
实例,如下所示:
func createTodoList(createdDate: Date, photos: Array<Data>? = nil) -> Void {
let todoList = TodoListModel()
todoList.createdDate = createdDate
if let photos = photos {
todoList.photos.append(objectsIn: photos)
}
TodoListFunctions.instance.addData(object: todoList)
}