RealmSwift - 如何在列表中存储数据

时间:2016-01-19 09:57:10

标签: ios iphone swift realm

我是编程新手,我想知道如何使用RealmSwift将数据存储在List中。

考虑以下模型:

import RealmSwift

class ScanResults: Object{
dynamic var id = 0
dynamic var resource = ""
dynamic var scanDate = ""
let ScanResultsDetail = List<ScanResultsDetails>()
}

class ScanResultsDetails: Object{
dynamic var scanner = ""
dynamic var result = ""
}

这是我存储新ScanResults的示例:

                let newResults = ScanResults()
                newResults.id = newResults.IncrementaID()
                newResults.resource = "Test"
                newResults.scanDate = "19.01.2016"
                do{
                    try uiRealm.write({ () -> Void in
                        uiRealm.add(newResults)
                    })

                }
                catch{
                }

我的问题是,如何在列表中存储数据?我无法弄清楚..你能举个例子吗?

1 个答案:

答案 0 :(得分:8)

我没有看到您在示例中将任何对象附加到ScanResultsDetail

以下是基于swift源代码(docs)的简单示例:

class Dog: Object {
    dynamic var name = ""
    dynamic var age = 0
}

class Person: Object {
    dynamic var name = ""
    let dogs = List<Dog>()
}

    let realm = try! Realm() // Create realm pointing to default file

    // Link objects
    let person = Person()
    person.name = "Tim"
    person.dogs.append(mydog)

    try! realm.write {
        realm.add(person)
    }