我有两节课。首先看起来像这样:
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
,当我尝试读取这些数据时,问题就开始了:SecondViewController
ViewDidLoad
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