以下是我想使用Realm存储的Course
对象:
class Course: Object {
var name: String = ""
var code: String = ""
var CRN: Int = 0
var capacity: Int = 0
var occupied: Int = 0
required init() {
super.init()
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
}
以下是我如何将对象写入Realm:
DispatchQueue.main.async {
try! self.realm.write {
self.realm.add(course)
}
}
这是我如何阅读对象:
for course in realm.objects(Course.self) {
self.courses.append(course)
self.tableView.reloadData()
}
我正在使用configure
函数设置UITableViewCell
Course
个对象:
func configure(withCourse course: Course) {
self.codeLabel.text = course.name
self.nameLabel.text = course.code
}
然而,这没有任何作用。
这是我必须要做的才能使UITableViewCell
正确配置:
self.codeLabel.text = course.value(forKeyPath: "name") as! String?
self.nameLabel.text = course.value(forKeyPath: "code") as! String?
如何访问其属性,而不是字典中的值?
答案 0 :(得分:3)
The properties in your model class are missing the dynamic
modifier. This modifier is necessary to ensure that Realm has an opportunity to intercept access to the properties, giving Realm an opportunity to read / write the data from the file on disk. Omitting these properties results in the Swift compiler accessing the instance variables directly, cutting Realm out of the loop. Your model class should look more like:
class Course: Object {
dynamic var name: String = ""
dynamic var code: String = ""
dynamic var CRN: Int = 0
dynamic var capacity: Int = 0
dynamic var occupied: Int = 0
}
None of the various init
methods included in your code snippet appear to be necessary either.