我只是想了解 Realm 并遇到了一个问题。我有一个这样的模型
class Template: Object {
dynamic var id = NSUUID().UUIDString
var pages = List<TemplatePage>()
}
class TemplatePage : Object {
var xPosition: Double = 0.0
var yPosition: Double = 0.0
}
现在,我正在执行以下代码:
class ViewController: UIViewController {
let realm = try! Realm()
var templatePages = [TemplatePage]()
override func viewDidLoad() {
super.viewDidLoad()
addTemplatePage(1.0, yPosition: 2.0)
//add more template pages
//[...]
//when all pages have been added create a template out of it.
addTemplate()
getXCoordinateOfFirstTemplatePage()
}
//Execute this method several times depending on the user interation
//here we only execute it once
func addTemplatePage(xPosition: Double, yPosition: Double) {
do {
let templatePage = TemplatePage()
templatePage.xPosition = xPosition
templatePage.yPosition = yPosition
try realm.write {
realm.add(templatePage)
}
templatePages.append(templatePage)
}
catch _ {
print("error while adding a template page")
}
}
//once all pages have been added create a template of of all recently added pages
func addTemplate() {
do {
let template = Template()
try realm.write {
template.pages.appendContentsOf(templatePages)
realm.add(template)
}
}
catch _ {
print("error while adding the template")
}
}
func getXCoordinateOfFirstTemplatePage() {
let template = realm.objects(Template)[0]
print(template.pages[0].xPosition)
}
}
当我运行此代码时,它会打印 0.0,即 TemplatePage xPosition 属性的默认值。但是,我不明白为什么,因为我实际上希望它打印 1.0。我不太明白为什么。有人可以给我一个提示吗?