[英]Realm relationship returns nil when it shouldn't
class Book: Object {
// (…)
var readingSessions: [ReadingSession] {
return linkingObjects(ReadingSession.self, forProperty: "book")
}
}
class ReadingSession: Object {
// (…)
var book: Book?
var aComputedProperty: Int {
print(self) // Prints ReadingSession { book = Book { (…) } (…) }
print(self.book) // Prints nil
// (…)
}
}
The code pretty much says it all. 代码几乎说明了一切。 If I print
self
from within my computed property it prints the related object among the other properties like I expect. 如果我从我的计算属性中打印
self
,它会像我期望的那样在其他属性中打印相关对象。 If I just try to get that object, though, it returns nil
. 但是,如果我只是尝试获取该对象,则返回
nil
。 Is that supposed to happen? 这应该发生吗? Am I doing something wrong?
难道我做错了什么?
Thanks in advance, 提前致谢,
Daniel 丹尼尔
Edit: It seems the problem isn't actually related to computed properties. 编辑:似乎问题实际上与计算属性无关。 Just calling this from a regular view controller gives me the same problem:
只是从常规视图控制器调用它给我同样的问题:
let session = ReadingSession()
// (…)
print(session) // This returns every property, including the Book
print(session.book) // This returns nil
It doesn't happen always, though. 但这并不总是发生。 On some parts of my code I do the same thing and it works as expected, in other parts this happens.
在我的代码的某些部分,我做同样的事情,它按预期工作,在其他部分发生这种情况。 So I guess I'm just making some silly mistake somewhere, but I have no idea what could be causing this.
所以我想我只是在某个地方犯了一些愚蠢的错误,但我不知道是什么原因引起的。
let realm = try! Realm()
let sessions = realm.objects(ReadingSession).filter("book = %@", user.selectedBook!).sorted("date")
let session = sessions[indexPath.row]
print(session.book) // prints nil
session.book = user.selectedBook!
print(session.book) // prints the correct book
I don't understand! 我不明白! I'm filtering the sessions based on a
Book
. 我正在根据一
Book
过滤会话。 When I print the filtered session's book shouldn't it return the book I used to filter it? 当我打印过滤后的会话的书不应该返回我用来过滤它的书吗? But it only works if I set its book property to that same book again!
但它只有在我再次将其书籍属性设置为同一本书时才有效!
You have to declare the user
property as dynamic var
to make this work: 您必须将
user
属性声明为dynamic var
才能使其工作:
class ReadingSession: Object {
dynamic var book: Book?
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.