持久化

@propertyWrapper
public struct Persisted<Value> where Value : _Persistable
extension Persisted: Decodable where Value: Decodable
extension Persisted: Encodable where Value: Encodable
extension Persisted: OptionalCodingWrapper where Value: ExpressibleByNilLiteral

@Persisted 用于声明应由 Realm 托管的对象子类的属性。

使用示例:

class MyModel: Object {
    // A basic property declaration. A property with no
    // default value supplied will default to `nil` for
    // Optional types, zero for numeric types, false for Bool,
    // an empty string/data, and a new random value for UUID
    // and ObjectID.
    @Persisted var basicIntProperty: Int

    // Custom default values can be specified with the
    // standard Swift syntax
    @Persisted var intWithCustomDefault: Int = 5

    // Properties can be indexed by passing `indexed: true`
    // to the initializer.
    @Persisted(indexed: true) var indexedString: String

    // Properties can set as the class's primary key by
    // passing `primaryKey: true` to the initializer
    @Persisted(primaryKey: true) var _id: ObjectId

    // List and set properties should always be declared
    // with `: List` rather than `= List()`
    @Persisted var listProperty: List<Int>
    @Persisted var setProperty: MutableSet<MyObject>

    // LinkingObjects properties require setting the source
    // object link property name in the initializer
    @Persisted(originProperty: "outgoingLink")
    var incomingLinks: LinkingObjects<OtherModel>

    // Properties which are not marked with @Persisted will
    // be ignored entirely by Realm.
    var ignoredProperty = true
}

可以通过将indexed: true传递给初始化器来对 Int、Bool、String、ObjectId 和 Date 属性进行索引。 对属性进行索引可提高对该属性进行相等查询的性能,但写入性能会稍差。 当前没有其他操作使用该索引。

A property can be set as the class’s primary key by passing primaryKey: true to the initializer. Compound primary keys are not supported, and setting more than one property as the primary key will throw an exception at runtime. Only Int, String, UUID and ObjectID properties can be made the primary key. The primary key property can only be mutated on unmanaged objects, and mutating it on an object which has been added to a Realm will throw an exception.

可以选择使用标准 Swift 语法为属性指定默认值。 如果未给出默认值,则在首次访问时生成一个值:对于所有可选类型,为nil ;对于数字类型为零;对于 Bool 为 false;为空字符串/数据;为 UUID 和 ObjectID 生成一个新的随机值。 List 和 MutableSet 属性不应通过将其设置为空 List/MutableSet 的默认值来定义。 这样做是可行的,但会导致访问 Realm 托管的对象时性能下降。同样,ObjectID 属性不应初始化为ObjectID.generate() ,因为这样做会导致生成额外的 ObjectID,然后在读取 Realm 时将其丢弃。

如果一个类至少有一个 @Persisted 属性,则 Realm 将忽略所有其他属性。 这意味着它们不会持久保存,也无法用于查询和其他需要托管属性的操作,例如排序和聚合。

@Persisted 不能用在任何地方,只能用作 对象 或 EmbeddedObject 子类上的 属性,并且尝试在其他地方使用它会导致运行时错误。

适用于以下位置: ValueDecodable

适用于以下位置: ValueEncodable

适用于以下位置: Value.PersistedType_Indexable

适用于以下位置: Value.PersistedType_PrimaryKey

适用于以下位置: ValueLinkingObjectsProtocol

  • 使用给定的源属性名称声明 LinkingObjects 属性。

    • 参数originProperty:链接到此对象的链接对象类型上的属性名称。

    声明

    迅速

    public init(originProperty: String)