为什么Realm建议List< T>使用"let"声明属性? [英] Why does Realm suggest that List<T> properties be declared using "let"?

查看:101
本文介绍了为什么Realm建议List< T>使用"let"声明属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一对多关系上的Realm文档声明其List<Dog>属性,使用let:

Realm's documentation on to-many relationships declares its List<Dog> property using let:

class Person: Object {
    // ... other property declarations
    let dogs = List<Dog>()
}

为什么使用dynamic var声明其他Realm属性类型时,为什么使用let声明此List<T>属性?

Why is this List<T> property declared using let when other Realm property types are declared using dynamic var?

推荐答案

List<T>属性应使用let声明,因为Realm无法拦截对这些属性的分配.分配给List<T>属性将不会导致您的更改持久化到Realm文件中.通过使用let而不是var声明属性,您可以注册Swift编译器来检测无法实现您期望的代码.

List<T> properties should be declared using let as Realm is unable to intercept assignment to these properties. Assigning to List<T> properties won't result in your changes being persisted to the Realm file. By declaring the property using let rather than var you enlist the Swift compiler to detect code that won't do what you intend.

您应该通过

Instead of assigning to List<T> properties you should mutate the existing value of the property via the methods that are part of the RangeReplaceableCollection protocol to which List<T> conforms.

例如,添加一条新狗:

person.dogs.append(lassie)

或者替换现有的狗:

person.dogs.replaceSubrange(0..<person.dogs.count, with: [fido, spot])


为什么?

领域模型类为访问基础数据库数据的持久属性自动实现获取器和设置器.为了提供这些getter和setter,必须使用dynamic修饰符声明属性.这个修饰符要求Swift通过getter和setter动态分配对属性的访问,而不是在编译时直接访问成员. dynamic修饰符有一个明显的限制:仅支持可以在Objective-C中表示的类型.这是因为Swift的动态调度是在Objective-C运行时之上构建的.正是这种限制阻止了Realm拦截对List<T>属性的分配.


Why?

Realm model classes automatically implement getters and setters for your persisted properties that access the underlying database data. In order to provide these getters and setters, your properties must be declared with the dynamic modifier. This modifier asks Swift to dynamically dispatch accesses to the properties via getters and setters rather than directly accessing the member at compile time. The dynamic modifier comes with a significant limitation: it is only supported for types that can be represented in Objective-C. This is because Swift's dynamic dispatch is built on top of the Objective-C runtime. It is this limitation that prevents Realm from intercepting assignments to List<T> properties.

这篇关于为什么Realm建议List&lt; T&gt;使用"let"声明属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆