11

我有两节课。首先看起来像这样:

class Person: Object {
    dynamic var owner: String?
    var dogs: List<Dogs>()
}

第二类看起来像这样:

class Dogs: Object {
    dynamic var name: String?
    dynamic var age: String?
}

现在在ViewController“viewDidLoad”中,我Person用空创建对象List并将其保存在领域

func viewDidLoad(){
    let person = Person()
    person.name = "Tomas"
    try! realm.write {
        realm.add(Person.self)
    }
}

它工作得很好,我可以创建Person,当我尝试读取这些数据时,问题就开始了:SecondViewControllerViewDidLoad

var persons: Results<Person>?

func viewDidLoad(){
    persons = try! realm.allObjects()
}

并尝试在按钮操作中添加新Dog功能:List

@IBAction func addDog(){
    let newDog = Dogs()
    newDog.name = "Rex"
    newDog.age = "2"

    persons[0].dogs.append(newDog)

    // in this place my application crashed

}

在这里,我的应用程序因信息而崩溃:Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.如何添加新Dog内容List以及如何更新人员 [0]?我使用 SWIFT 3.0

4

4 回答 4

11

persons属性是 type Results<Person>,它是一个包含Person由 Realm 管理的对象的集合。为了修改托管对象的属性,例如将新元素附加到列表属性,您需要在写入事务中。

try! realm.write {
    persons[0].dogs.append(newDog)
}
于 2016-07-20T20:29:59.773 回答
2

写这样的东西:

if let person = persons?[0] {
    person.dogs.append(newDog)
}

try! realm.write {
    realm.add(person, update: true)
}

请检查你是如何得到的realm。每次打电话defaultRealm,你都会得到新的境界。

于 2016-07-20T20:25:38.797 回答
1

旁注:除了在解决您的问题的写入事务中添加代码外,您还可以Person按名称查询如下...

@IBAction func addDog(){
    let newDog = Dogs()
    newDog.name = "Rex"
    newDog.age = "2"

    let personName = realm.objects(Person.self).filter("name = 'Tomas'").first!

    try! realm.write {
        personName.dogs.append(newDog)
    }
}
于 2017-04-27T11:42:36.703 回答
-1

为领域数据库添加对象

class Task : Object {
    @objc dynamic var id : Int = 0
    @objc dynamic var name = ""
    @objc dynamic var phone = ""
    @objc dynamic var address = ""
}
@IBAction func buttonSave(_ sender: Any) {
        let realm  = try! Realm()
        let user = Task()
        user.id = 0
        user.name = (txtName.text! as NSString) as String
        user.phone = (txtPhone.text! as NSString) as String
        user.address = (txtAddress.text! as NSString) as String
        try! realm.write {
            realm.add(user)
            print("user:",user.name)
        }



    }
于 2019-03-07T04:39:50.457 回答