我在下面给出了两个课程。我想对这些对象执行(添加,更新和删除)等操作。
Class CheckOutImageList 是一个包含图像的对象数组,Class CheckOutDetail 是一个包含图像对象的对象。
class CheckOutImageList: Object {
@objc dynamic var imageUrl = ""
@objc dynamic var imageName = "test"
@objc dynamic var isProfile = Bool()
@objc dynamic var imageDesc = ""
override static func primaryKey() -> String? {
return "imageName"
}
}
class CheckOutDetail: Object {
@objc dynamic var taskId = 0
var imageList = List<CheckOutImageList>()
@objc dynamic var remarks = ""
@objc dynamic var isFollowUp = Bool()
@objc dynamic var followDate = ""
@objc dynamic var followTime = ""
override static func primaryKey() -> String? {
return "taskId"
}
}
我可以在 CheckOutDetail 类上执行添加和更新操作,但需要帮助在图像列表数组中添加,更新和删除。
答案 0 :(得分:0)
您可以将CheckOutImageList
元素附加到对象CheckOutDetail
。
试试这个:
let realmIn = try! Realm()
var checkOutDetail = CheckOutDetail()
checkOutDetail.taskId = 1
checkOutDetail.imageList = "imageList"
checkOutDetail.isFollowUp = "isFollowUp "
checkOutDetail.followTime = "followTime"
// You can use for to append multiple elements to list
let newCheckOutImageList = CheckOutImageList()
newCheckOutImageList.imageUrl = "url"
nweCheckOutImageList.imageName = "imageName"
newCheckOutImageList.isProfile = "isProfile"
newCheckOutImageList.imageDesc = "imageDesc"
checkOutDetail.imageList.append(newCheckOutImageList)
try! realmIn.write {
realmIn.add(checkOutDetail, update: true)
}
答案 1 :(得分:0)
要解决此问题,我在对象中进行了一些更改。我做了什么,我只是为 CheckOutDetails 和 CheckOutImageList 创建两个单独的对象,如下所示:
class CheckOutImageList: Object {
@objc dynamic var taskId = 0
@objc dynamic var imageUrl = ""
@objc dynamic var imageName = ""
@objc dynamic var isProfile = Bool()
@objc dynamic var imageDesc = ""
override static func primaryKey() -> String? {
return "imageName"
}
}
class CheckOutDetail: Object {
@objc dynamic var taskId = 0
@objc dynamic var remarks = ""
@objc dynamic var isFollowUp = Bool()
@objc dynamic var followDate = ""
@objc dynamic var followTime = ""
override static func primaryKey() -> String? {
return "taskId"
}
}
//Code to update old data or add new image data in the CheckOutImageList Object
if self.checkImageNameExist(imageName: imgDetail.fileName) {
try! realm.write {
realm.add(obj, update: true) //obj is of type CheckOutImageList
}
} else {
try! realm.write {
realm.add(obj)
}
}
//Function will return true if primary key already exist else return false
func checkImageNameExist(imageName: String) -> Bool {
return realm.object(ofType: CheckOutImageList.self, forPrimaryKey: imageName) != nil
}
并使用 CheckOutDetails 中的taskId作为外键来获取相同ID的详细信息。