I'm just trying to understand Realm and ran into an issue. I have a model like this
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
}
Now, I'm executing the following code:
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)
}
}
When I run this code, it prints 0.0, the default value of the TemplatePage xPosition property. However, I don't understand why because I would actually expect it to print 1.0. I don't quite get why. Can someone give me a hint?
I faced similar issues. Whenever you use nested class like you are doing with TemplatePage
make the variables dynamic.
Change
var xPosition: Double = 0.0
var yPosition: Double = 0.0
to
dynamic var xPosition: Double = 0.0
dynamic var yPosition: Double = 0.0
I tried few things with 'RealmSwift' for Swift 4.2 to store Double value in Realm. The following worked well. @objc is for Swift version and also Realm does not allow me to define Double as Optional like Double? so I gave the default value.
@objc dynamic var height: Double = 0.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.