Object.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import Foundation
  19. import Realm
  20. import Realm.Private
  21. /**
  22. `Object` is a class used to define Realm model objects.
  23. In Realm you define your model classes by subclassing `Object` and adding properties to be managed.
  24. You then instantiate and use your custom subclasses instead of using the `Object` class directly.
  25. ```swift
  26. class Dog: Object {
  27. @Persisted var name: String
  28. @Persisted var adopted: Bool
  29. @Persisted var siblings: List<Dog>
  30. }
  31. ```
  32. ### Supported property types
  33. - `String`
  34. - `Int`, `Int8`, `Int16`, `Int32`, `Int64`
  35. - `Float`
  36. - `Double`
  37. - `Bool`
  38. - `Date`
  39. - `Data`
  40. - `Decimal128`
  41. - `ObjectId`
  42. - `UUID`
  43. - `AnyRealmValue`
  44. - Any RawRepresentable enum whose raw type is a legal property type. Enums
  45. must explicitly be marked as conforming to `PersistableEnum`.
  46. - `Object` subclasses, to model many-to-one relationships
  47. - `EmbeddedObject` subclasses, to model owning one-to-one relationships
  48. All of the types above may also be `Optional`, with the exception of
  49. `AnyRealmValue`. `Object` and `EmbeddedObject` subclasses *must* be Optional.
  50. In addition to individual values, three different collection types are supported:
  51. - `List<Element>`: an ordered mutable collection similar to `Array`.
  52. - `MutableSet<Element>`: an unordered uniquing collection similar to `Set`.
  53. - `Map<String, Element>`: an unordered key-value collection similar to `Dictionary`.
  54. The Element type of collections may be any of the supported non-collection
  55. property types listed above. Collections themselves may not be Optional, but
  56. the values inside them may be, except for lists and sets of `Object` or
  57. `EmbeddedObject` subclasses.
  58. Finally, `LinkingObjects` properties can be used to track which objects link
  59. to this one.
  60. All properties which should be stored by Realm must be explicitly marked with
  61. `@Persisted`. Any properties not marked with `@Persisted` will be ignored
  62. entirely by Realm, and may be of any type.
  63. ### Querying
  64. You can retrieve all objects of a given type from a Realm by calling the `objects(_:)` instance method.
  65. ### Relationships
  66. See our [Swift guide](https://docs.mongodb.com/realm/sdk/swift/fundamentals/relationships/) for more details.
  67. */
  68. public typealias Object = RealmSwiftObject
  69. extension Object: _RealmCollectionValueInsideOptional {
  70. // MARK: Initializers
  71. /**
  72. Creates an unmanaged instance of a Realm object.
  73. The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
  74. dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
  75. managed property. An exception will be thrown if any required properties are not present and those properties were
  76. not defined with default values.
  77. When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
  78. the properties defined in the model.
  79. Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm.
  80. - parameter value: The value used to populate the object.
  81. */
  82. public convenience init(value: Any) {
  83. self.init()
  84. RLMInitializeWithValue(self, value, .partialPrivateShared())
  85. }
  86. // MARK: Properties
  87. /// The Realm which manages the object, or `nil` if the object is unmanaged.
  88. public var realm: Realm? {
  89. if let rlmReam = RLMObjectBaseRealm(self) {
  90. return Realm(rlmReam)
  91. }
  92. return nil
  93. }
  94. /// The object schema which lists the managed properties for the object.
  95. public var objectSchema: ObjectSchema {
  96. return ObjectSchema(RLMObjectBaseObjectSchema(self)!)
  97. }
  98. /// Indicates if the object can no longer be accessed because it is now invalid.
  99. ///
  100. /// An object can no longer be accessed if the object has been deleted from the Realm that manages it, or if
  101. /// `invalidate()` is called on that Realm. This property is key-value observable.
  102. @objc dynamic open override var isInvalidated: Bool { return super.isInvalidated }
  103. /// A human-readable description of the object.
  104. open override var description: String { return super.description }
  105. /**
  106. WARNING: This is an internal helper method not intended for public use.
  107. It is not considered part of the public API.
  108. :nodoc:
  109. */
  110. public override final class func _getProperties() -> [RLMProperty] {
  111. return ObjectUtil.getSwiftProperties(self)
  112. }
  113. // MARK: Object Customization
  114. /**
  115. Override this method to specify the name of a property to be used as the primary key.
  116. Only properties of types `String`, `Int`, `ObjectId` and `UUID` can be
  117. designated as the primary key. Primary key properties enforce uniqueness
  118. for each value whenever the property is set, which incurs minor overhead.
  119. Indexes are created automatically for primary key properties.
  120. - warning: This function is only applicable to legacy property declarations
  121. using `@objc`. When using `@Persisted`, use
  122. `@Persisted(primaryKey: true)` instead.
  123. - returns: The name of the property designated as the primary key, or
  124. `nil` if the model has no primary key.
  125. */
  126. @objc open class func primaryKey() -> String? { return nil }
  127. /**
  128. Override this method to specify the names of properties to ignore. These
  129. properties will not be managed by the Realm that manages the object.
  130. - warning: This function is only applicable to legacy property declarations
  131. using `@objc`. When using `@Persisted`, any properties not
  132. marked with `@Persisted` are automatically ignored.
  133. - returns: An array of property names to ignore.
  134. */
  135. @objc open class func ignoredProperties() -> [String] { return [] }
  136. /**
  137. Returns an array of property names for properties which should be indexed.
  138. Only string, integer, boolean, `Date`, and `NSDate` properties are supported.
  139. - warning: This function is only applicable to legacy property declarations
  140. using `@objc`. When using `@Persisted`, use
  141. `@Persisted(indexed: true)` instead.
  142. - returns: An array of property names.
  143. */
  144. @objc open class func indexedProperties() -> [String] { return [] }
  145. /**
  146. Override this method to specify a map of public-private property names.
  147. This will set a different persisted property name on the Realm, and allows using the public name
  148. for any operation with the property. (Ex: Queries, Sorting, ...).
  149. This very helpful if you need to map property names from your `Device Sync` JSON schema
  150. to local property names.
  151. ```swift
  152. class Person: Object {
  153. @Persisted var firstName: String
  154. @Persisted var birthDate: Date
  155. @Persisted var age: Int
  156. override class public func propertiesMapping() -> [String : String] {
  157. ["firstName": "first_name",
  158. "birthDate": "birth_date"]
  159. }
  160. }
  161. ```
  162. - note: Only property that have a different column name have to be added to the properties mapping
  163. dictionary.
  164. - note: In a migration block, when enumerating an old property with a public/private name, you will have to use
  165. the old column name instead of the public one to retrieve the property value.
  166. ```swift
  167. let migrationBlock = { migration, oldSchemaVersion in
  168. migration.enumerateObjects(ofType: "Person", { oldObj, newObj in
  169. let oldPropertyValue = oldObj!["first_name"] as! String
  170. // Use this value in migration
  171. })
  172. }
  173. ```
  174. This has to be done as well when renaming a property.
  175. ```swift
  176. let migrationBlock = { migration, oldSchemaVersion in
  177. migration.renameProperty(onType: "Person", from: "first_name", to: "complete_name")
  178. }
  179. ```
  180. - returns: A dictionary of public-private property names.
  181. */
  182. @objc open override class func propertiesMapping() -> [String: String] { return [:] }
  183. /// :nodoc:
  184. @available(*, unavailable, renamed: "propertiesMapping", message: "`_realmColumnNames` private API is unavailable in our Swift SDK, please use the override `.propertiesMapping()` instead.")
  185. @objc open override class func _realmColumnNames() -> [String: String] { return [:] }
  186. // MARK: Key-Value Coding & Subscripting
  187. /// Returns or sets the value of the property with the given name.
  188. @objc open subscript(key: String) -> Any? {
  189. get {
  190. RLMDynamicGetByName(self, key)
  191. }
  192. set {
  193. dynamicSet(object: self, key: key, value: newValue)
  194. }
  195. }
  196. // MARK: Notifications
  197. /**
  198. Registers a block to be called each time the object changes.
  199. The block will be asynchronously called after each write transaction which
  200. deletes the object or modifies any of the managed properties of the object,
  201. including self-assignments that set a property to its existing value.
  202. For write transactions performed on different threads or in different
  203. processes, the block will be called when the managing Realm is
  204. (auto)refreshed to a version including the changes, while for local write
  205. transactions it will be called at some point in the future after the write
  206. transaction is committed.
  207. If no key paths are given, the block will be executed on any insertion,
  208. modification, or deletion for all object properties and the properties of
  209. any nested, linked objects. If a key path or key paths are provided,
  210. then the block will be called for changes which occur only on the
  211. provided key paths. For example, if:
  212. ```swift
  213. class Dog: Object {
  214. @Persisted var name: String
  215. @Persisted var adopted: Bool
  216. @Persisted var siblings: List<Dog>
  217. }
  218. // ... where `dog` is a managed Dog object.
  219. dog.observe(keyPaths: ["adopted"], { changes in
  220. // ...
  221. })
  222. ```
  223. - The above notification block fires for changes to the
  224. `adopted` property, but not for any changes made to `name`.
  225. - If the observed key path were `["siblings"]`, then any insertion,
  226. deletion, or modification to the `siblings` list will trigger the block. A change to
  227. `someSibling.name` would not trigger the block (where `someSibling`
  228. is an element contained in `siblings`)
  229. - If the observed key path were `["siblings.name"]`, then any insertion or
  230. deletion to the `siblings` list would trigger the block. For objects
  231. contained in the `siblings` list, only modifications to their `name` property
  232. will trigger the block.
  233. - note: Multiple notification tokens on the same object which filter for
  234. separate key paths *do not* filter exclusively. If one key path
  235. change is satisfied for one notification token, then all notification
  236. token blocks for that object will execute.
  237. If no queue is given, notifications are delivered via the standard run
  238. loop, and so can't be delivered while the run loop is blocked by other
  239. activity. If a queue is given, notifications are delivered to that queue
  240. instead. When notifications can't be delivered instantly, multiple
  241. notifications may be coalesced into a single notification.
  242. Unlike with `List` and `Results`, there is no "initial" callback made after
  243. you add a new notification block.
  244. Only objects which are managed by a Realm can be observed in this way. You
  245. must retain the returned token for as long as you want updates to be sent
  246. to the block. To stop receiving updates, call `invalidate()` on the token.
  247. It is safe to capture a strong reference to the observed object within the
  248. callback block. There is no retain cycle due to that the callback is
  249. retained by the returned token and not by the object itself.
  250. - warning: This method cannot be called during a write transaction, or when
  251. the containing Realm is read-only.
  252. - parameter keyPaths: Only properties contained in the key paths array will trigger
  253. the block when they are modified. If `nil`, notifications
  254. will be delivered for any property change on the object.
  255. String key paths which do not correspond to a valid a property
  256. will throw an exception.
  257. See description above for more detail on linked properties.
  258. - parameter queue: The serial dispatch queue to receive notification on. If
  259. `nil`, notifications are delivered to the current thread.
  260. - parameter block: The block to call with information about changes to the object.
  261. - returns: A token which must be held for as long as you want updates to be delivered.
  262. */
  263. public func observe<T: RLMObjectBase>(keyPaths: [String]? = nil,
  264. on queue: DispatchQueue? = nil,
  265. _ block: @escaping (ObjectChange<T>) -> Void) -> NotificationToken {
  266. _observe(keyPaths: keyPaths, on: queue, block)
  267. }
  268. /**
  269. Registers a block to be called each time the object changes.
  270. The block will be asynchronously called after each write transaction which
  271. deletes the object or modifies any of the managed properties of the object,
  272. including self-assignments that set a property to its existing value.
  273. For write transactions performed on different threads or in different
  274. processes, the block will be called when the managing Realm is
  275. (auto)refreshed to a version including the changes, while for local write
  276. transactions it will be called at some point in the future after the write
  277. transaction is committed.
  278. If no key paths are given, the block will be executed on any insertion,
  279. modification, or deletion for all object properties and the properties of
  280. any nested, linked objects. If a key path or key paths are provided,
  281. then the block will be called for changes which occur only on the
  282. provided key paths. For example, if:
  283. ```swift
  284. class Dog: Object {
  285. @Persisted var name: String
  286. @Persisted var adopted: Bool
  287. @Persisted var siblings: List<Dog>
  288. }
  289. // ... where `dog` is a managed Dog object.
  290. dog.observe(keyPaths: [\Dog.adopted], { changes in
  291. // ...
  292. })
  293. ```
  294. - The above notification block fires for changes to the
  295. `adopted` property, but not for any changes made to `name`.
  296. - If the observed key path were `[\Dog.siblings]`, then any insertion,
  297. deletion, or modification to the `siblings` list will trigger the block. A change to
  298. `someSibling.name` would not trigger the block (where `someSibling`
  299. is an element contained in `siblings`)
  300. - If the observed key path were `[\Dog.siblings.name]`, then any insertion or
  301. deletion to the `siblings` list would trigger the block. For objects
  302. contained in the `siblings` list, only modifications to their `name` property
  303. will trigger the block.
  304. - note: Multiple notification tokens on the same object which filter for
  305. separate key paths *do not* filter exclusively. If one key path
  306. change is satisfied for one notification token, then all notification
  307. token blocks for that object will execute.
  308. If no queue is given, notifications are delivered via the standard run
  309. loop, and so can't be delivered while the run loop is blocked by other
  310. activity. If a queue is given, notifications are delivered to that queue
  311. instead. When notifications can't be delivered instantly, multiple
  312. notifications may be coalesced into a single notification.
  313. Unlike with `List` and `Results`, there is no "initial" callback made after
  314. you add a new notification block.
  315. Only objects which are managed by a Realm can be observed in this way. You
  316. must retain the returned token for as long as you want updates to be sent
  317. to the block. To stop receiving updates, call `invalidate()` on the token.
  318. It is safe to capture a strong reference to the observed object within the
  319. callback block. There is no retain cycle due to that the callback is
  320. retained by the returned token and not by the object itself.
  321. - warning: This method cannot be called during a write transaction, or when
  322. the containing Realm is read-only.
  323. - parameter keyPaths: Only properties contained in the key paths array will trigger
  324. the block when they are modified. If `nil`, notifications
  325. will be delivered for any property change on the object.
  326. See description above for more detail on linked properties.
  327. - parameter queue: The serial dispatch queue to receive notification on. If
  328. `nil`, notifications are delivered to the current thread.
  329. - parameter block: The block to call with information about changes to the object.
  330. - returns: A token which must be held for as long as you want updates to be delivered.
  331. */
  332. public func observe<T: ObjectBase>(keyPaths: [PartialKeyPath<T>],
  333. on queue: DispatchQueue? = nil,
  334. _ block: @escaping (ObjectChange<T>) -> Void) -> NotificationToken {
  335. _observe(keyPaths: keyPaths.map(_name(for:)), on: queue, block)
  336. }
  337. #if swift(>=5.8)
  338. /**
  339. Registers a block to be called each time the object changes.
  340. The block will be asynchronously called on the given actor's executor after
  341. each write transaction which deletes the object or modifies any of the managed
  342. properties of the object, including self-assignments that set a property to its
  343. existing value. The block is passed a copy of the object isolated to the
  344. requested actor which can be safely used on that actor along with information
  345. about what changed.
  346. For write transactions performed on different threads or in different
  347. processes, the block will be called when the managing Realm is
  348. (auto)refreshed to a version including the changes, while for local write
  349. transactions it will be called at some point in the future after the write
  350. transaction is committed.
  351. Only objects which are managed by a Realm can be observed in this way. You
  352. must retain the returned token for as long as you want updates to be sent
  353. to the block. To stop receiving updates, call `invalidate()` on the token.
  354. By default, only direct changes to the object's properties will produce
  355. notifications, and not changes to linked objects. Note that this is different
  356. from collection change notifications. If a non-nil, non-empty keypath array is
  357. passed in, only changes to the properties identified by those keypaths will
  358. produce change notifications. The keypaths may traverse link properties to
  359. receive information about changes to linked objects.
  360. - warning: This method cannot be called during a write transaction, or when
  361. the containing Realm is read-only.
  362. - parameter actor: The actor to isolate notifications to.
  363. - parameter block: The block to call with information about changes to the object.
  364. - returns: A token which must be held for as long as you want updates to be delivered.
  365. */
  366. @available(macOS 10.15, tvOS 13.0, iOS 13.0, watchOS 6.0, *)
  367. @_unsafeInheritExecutor
  368. public func observe<A: Actor, T: Object>(
  369. keyPaths: [String]? = nil, on actor: A,
  370. _ block: @Sendable @escaping (isolated A, ObjectChange<T>) -> Void
  371. ) async -> NotificationToken {
  372. await with(self, on: actor) { actor, obj in
  373. await obj._observe(keyPaths: keyPaths, on: actor, block)
  374. } ?? NotificationToken()
  375. }
  376. /**
  377. Registers a block to be called each time the object changes.
  378. The block will be asynchronously called on the given actor's executor after
  379. each write transaction which deletes the object or modifies any of the managed
  380. properties of the object, including self-assignments that set a property to its
  381. existing value. The block is passed a copy of the object isolated to the
  382. requested actor which can be safely used on that actor along with information
  383. about what changed.
  384. For write transactions performed on different threads or in different
  385. processes, the block will be called when the managing Realm is
  386. (auto)refreshed to a version including the changes, while for local write
  387. transactions it will be called at some point in the future after the write
  388. transaction is committed.
  389. Only objects which are managed by a Realm can be observed in this way. You
  390. must retain the returned token for as long as you want updates to be sent
  391. to the block. To stop receiving updates, call `invalidate()` on the token.
  392. By default, only direct changes to the object's properties will produce
  393. notifications, and not changes to linked objects. Note that this is different
  394. from collection change notifications. If a non-nil, non-empty keypath array is
  395. passed in, only changes to the properties identified by those keypaths will
  396. produce change notifications. The keypaths may traverse link properties to
  397. receive information about changes to linked objects.
  398. - warning: This method cannot be called during a write transaction, or when
  399. the containing Realm is read-only.
  400. - parameter actor: The actor to isolate notifications to.
  401. - parameter block: The block to call with information about changes to the object.
  402. - returns: A token which must be held for as long as you want updates to be delivered.
  403. */
  404. @available(macOS 10.15, tvOS 13.0, iOS 13.0, watchOS 6.0, *)
  405. @_unsafeInheritExecutor
  406. public func observe<A: Actor, T: Object>(
  407. keyPaths: [PartialKeyPath<T>], on actor: A,
  408. _ block: @Sendable @escaping (isolated A, ObjectChange<T>) -> Void
  409. ) async -> NotificationToken {
  410. await observe(keyPaths: keyPaths.map(_name(for:)), on: actor, block)
  411. }
  412. #endif // swift(>=5.8)
  413. // MARK: Dynamic list
  414. /**
  415. Returns a list of `DynamicObject`s for a given property name.
  416. - warning: This method is useful only in specialized circumstances, for example, when building
  417. components that integrate with Realm. If you are simply building an app on Realm, it is
  418. recommended to use instance variables or cast the values returned from key-value coding.
  419. - parameter propertyName: The name of the property.
  420. - returns: A list of `DynamicObject`s.
  421. :nodoc:
  422. */
  423. public func dynamicList(_ propertyName: String) -> List<DynamicObject> {
  424. if let dynamic = self as? DynamicObject {
  425. return dynamic[propertyName] as! List<DynamicObject>
  426. }
  427. let list = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
  428. return List<DynamicObject>(collection: list._rlmCollection as! RLMArray<AnyObject>)
  429. }
  430. // MARK: Dynamic set
  431. /**
  432. Returns a set of `DynamicObject`s for a given property name.
  433. - warning: This method is useful only in specialized circumstances, for example, when building
  434. components that integrate with Realm. If you are simply building an app on Realm, it is
  435. recommended to use instance variables or cast the values returned from key-value coding.
  436. - parameter propertyName: The name of the property.
  437. - returns: A set of `DynamicObject`s.
  438. :nodoc:
  439. */
  440. public func dynamicMutableSet(_ propertyName: String) -> MutableSet<DynamicObject> {
  441. if let dynamic = self as? DynamicObject {
  442. return dynamic[propertyName] as! MutableSet<DynamicObject>
  443. }
  444. let set = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
  445. return MutableSet<DynamicObject>(collection: set._rlmCollection as! RLMSet<AnyObject>)
  446. }
  447. // MARK: Dynamic map
  448. /**
  449. Returns a map of `DynamicObject`s for a given property name.
  450. - warning: This method is useful only in specialized circumstances, for example, when building
  451. components that integrate with Realm. If you are simply building an app on Realm, it is
  452. recommended to use instance variables or cast the values returned from key-value coding.
  453. - parameter propertyName: The name of the property.
  454. - returns: A map with a given key type with `DynamicObject` as the value.
  455. :nodoc:
  456. */
  457. public func dynamicMap<Key: _MapKey>(_ propertyName: String) -> Map<Key, DynamicObject?> {
  458. if let dynamic = self as? DynamicObject {
  459. return dynamic[propertyName] as! Map<Key, DynamicObject?>
  460. }
  461. let base = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
  462. return Map<Key, DynamicObject?>(objc: base._rlmCollection as! RLMDictionary<AnyObject, AnyObject>)
  463. }
  464. // MARK: Comparison
  465. /**
  466. Returns whether two Realm objects are the same.
  467. Objects are considered the same if and only if they are both managed by the same
  468. Realm and point to the same underlying object in the database.
  469. - note: Equality comparison is implemented by `isEqual(_:)`. If the object type
  470. is defined with a primary key, `isEqual(_:)` behaves identically to this
  471. method. If the object type is not defined with a primary key,
  472. `isEqual(_:)` uses the `NSObject` behavior of comparing object identity.
  473. This method can be used to compare two objects for database equality
  474. whether or not their object type defines a primary key.
  475. - parameter object: The object to compare the receiver to.
  476. */
  477. public func isSameObject(as object: Object?) -> Bool {
  478. return RLMObjectBaseAreEqual(self, object)
  479. }
  480. }
  481. extension Object: ThreadConfined {
  482. /**
  483. Indicates if this object is frozen.
  484. - see: `Object.freeze()`
  485. */
  486. public var isFrozen: Bool { return realm?.isFrozen ?? false }
  487. /**
  488. Returns a frozen (immutable) snapshot of this object.
  489. The frozen copy is an immutable object which contains the same data as this
  490. object currently contains, but will not update when writes are made to the
  491. containing Realm. Unlike live objects, frozen objects can be accessed from any
  492. thread.
  493. - warning: Holding onto a frozen object for an extended period while performing write
  494. transaction on the Realm may result in the Realm file growing to large sizes. See
  495. `Realm.Configuration.maximumNumberOfActiveVersions` for more information.
  496. - warning: This method can only be called on a managed object.
  497. */
  498. public func freeze() -> Self {
  499. guard let realm = realm else { throwRealmException("Unmanaged objects cannot be frozen.") }
  500. return realm.freeze(self)
  501. }
  502. /**
  503. Returns a live (mutable) reference of this object.
  504. This method creates a managed accessor to a live copy of the same frozen object.
  505. Will return self if called on an already live object.
  506. */
  507. public func thaw() -> Self? {
  508. guard let realm = realm else { throwRealmException("Unmanaged objects cannot be thawed.") }
  509. return realm.thaw(self)
  510. }
  511. }
  512. /**
  513. Information about a specific property which changed in an `Object` change notification.
  514. */
  515. @frozen public struct PropertyChange {
  516. /**
  517. The name of the property which changed.
  518. */
  519. public let name: String
  520. /**
  521. Value of the property before the change occurred. This is not supplied if
  522. the change happened on the same thread as the notification and for `List`
  523. properties.
  524. For object properties this will give the object which was previously
  525. linked to, but that object will have its new values and not the values it
  526. had before the changes. This means that `previousValue` may be a deleted
  527. object, and you will need to check `isInvalidated` before accessing any
  528. of its properties.
  529. */
  530. public let oldValue: Any?
  531. /**
  532. The value of the property after the change occurred. This is not supplied
  533. for `List` properties and will always be nil.
  534. */
  535. public let newValue: Any?
  536. }
  537. /**
  538. Information about the changes made to an object which is passed to `Object`'s
  539. notification blocks.
  540. */
  541. @frozen public enum ObjectChange<T> {
  542. /**
  543. Errors can no longer occur. This case is unused and will be removed in the
  544. next major version.
  545. */
  546. case error(_ error: NSError)
  547. /**
  548. One or more of the properties of the object have been changed.
  549. */
  550. case change(_: T, _: [PropertyChange])
  551. /// The object has been deleted from the Realm.
  552. case deleted
  553. internal init(object: T?, names: [String]?, oldValues: [Any]?, newValues: [Any]?) {
  554. guard let names = names, let newValues = newValues, let object = object else {
  555. self = .deleted
  556. return
  557. }
  558. self = .change(object, (0..<newValues.count).map { i in
  559. PropertyChange(name: names[i], oldValue: oldValues?[i], newValue: newValues[i])
  560. })
  561. }
  562. }
  563. /// Object interface which allows untyped getters and setters for Objects.
  564. /// :nodoc:
  565. @objc(RealmSwiftDynamicObject)
  566. @dynamicMemberLookup
  567. public final class DynamicObject: Object {
  568. public override subscript(key: String) -> Any? {
  569. get {
  570. let value = RLMDynamicGetByName(self, key).flatMap(coerceToNil)
  571. if let array = value as? RLMArray<AnyObject> {
  572. return list(from: array)
  573. }
  574. if let set = value as? RLMSet<AnyObject> {
  575. return mutableSet(from: set)
  576. }
  577. if let dictionary = value as? RLMDictionary<AnyObject, AnyObject> {
  578. return map(from: dictionary)
  579. }
  580. return value
  581. }
  582. set(value) {
  583. RLMDynamicValidatedSet(self, key, value)
  584. }
  585. }
  586. public subscript(dynamicMember member: String) -> Any? {
  587. get {
  588. self[member]
  589. }
  590. set(value) {
  591. self[member] = value
  592. }
  593. }
  594. /// :nodoc:
  595. public override func value(forUndefinedKey key: String) -> Any? {
  596. return self[key]
  597. }
  598. /// :nodoc:
  599. public override func setValue(_ value: Any?, forUndefinedKey key: String) {
  600. self[key] = value
  601. }
  602. /// :nodoc:
  603. public override class func shouldIncludeInDefaultSchema() -> Bool {
  604. return false
  605. }
  606. override public class func sharedSchema() -> RLMObjectSchema? {
  607. nil
  608. }
  609. private func list(from array: RLMArray<AnyObject>) -> Any {
  610. switch array.type {
  611. case .int:
  612. return array.isOptional ? List<Int?>(collection: array) : List<Int>(collection: array)
  613. case .double:
  614. return array.isOptional ? List<Double?>(collection: array) : List<Double>(collection: array)
  615. case .float:
  616. return array.isOptional ? List<Float?>(collection: array) : List<Float>(collection: array)
  617. case .decimal128:
  618. return array.isOptional ? List<Decimal128?>(collection: array) : List<Decimal128>(collection: array)
  619. case .bool:
  620. return array.isOptional ? List<Bool?>(collection: array) : List<Bool>(collection: array)
  621. case .UUID:
  622. return array.isOptional ? List<UUID?>(collection: array) : List<UUID>(collection: array)
  623. case .string:
  624. return array.isOptional ? List<String?>(collection: array) : List<String>(collection: array)
  625. case .data:
  626. return array.isOptional ? List<Data?>(collection: array) : List<Data>(collection: array)
  627. case .date:
  628. return array.isOptional ? List<Date?>(collection: array) : List<Date>(collection: array)
  629. case .any:
  630. return List<AnyRealmValue>(collection: array)
  631. case .linkingObjects:
  632. throwRealmException("Unsupported migration type of 'LinkingObjects' for type 'List'.")
  633. case .objectId:
  634. return array.isOptional ? List<ObjectId?>(collection: array) : List<ObjectId>(collection: array)
  635. case .object:
  636. return List<DynamicObject>(collection: array)
  637. }
  638. }
  639. private func mutableSet(from set: RLMSet<AnyObject>) -> Any {
  640. switch set.type {
  641. case .int:
  642. return set.isOptional ? MutableSet<Int?>(collection: set) : MutableSet<Int>(collection: set)
  643. case .double:
  644. return set.isOptional ? MutableSet<Double?>(collection: set) : MutableSet<Double>(collection: set)
  645. case .float:
  646. return set.isOptional ? MutableSet<Float?>(collection: set) : MutableSet<Float>(collection: set)
  647. case .decimal128:
  648. return set.isOptional ? MutableSet<Decimal128?>(collection: set) : MutableSet<Decimal128>(collection: set)
  649. case .bool:
  650. return set.isOptional ? MutableSet<Bool?>(collection: set) : MutableSet<Bool>(collection: set)
  651. case .UUID:
  652. return set.isOptional ? MutableSet<UUID?>(collection: set) : MutableSet<UUID>(collection: set)
  653. case .string:
  654. return set.isOptional ? MutableSet<String?>(collection: set) : MutableSet<String>(collection: set)
  655. case .data:
  656. return set.isOptional ? MutableSet<Data?>(collection: set) : MutableSet<Data>(collection: set)
  657. case .date:
  658. return set.isOptional ? MutableSet<Date?>(collection: set) : MutableSet<Date>(collection: set)
  659. case .any:
  660. return MutableSet<AnyRealmValue>(collection: set)
  661. case .linkingObjects:
  662. throwRealmException("Unsupported migration type of 'LinkingObjects' for type 'MutableSet'.")
  663. case .objectId:
  664. return set.isOptional ? MutableSet<ObjectId?>(collection: set) : MutableSet<ObjectId>(collection: set)
  665. case .object:
  666. return MutableSet<DynamicObject>(collection: set)
  667. }
  668. }
  669. private func map(from dictionary: RLMDictionary<AnyObject, AnyObject>) -> Any {
  670. switch dictionary.type {
  671. case .int:
  672. return dictionary.isOptional ? Map<String, Int?>(objc: dictionary) : Map<String, Int>(objc: dictionary)
  673. case .double:
  674. return dictionary.isOptional ? Map<String, Double?>(objc: dictionary) : Map<String, Double>(objc: dictionary)
  675. case .float:
  676. return dictionary.isOptional ? Map<String, Float?>(objc: dictionary) : Map<String, Float>(objc: dictionary)
  677. case .decimal128:
  678. return dictionary.isOptional ? Map<String, Decimal128?>(objc: dictionary) : Map<String, Decimal128>(objc: dictionary)
  679. case .bool:
  680. return dictionary.isOptional ? Map<String, Bool?>(objc: dictionary) : Map<String, Bool>(objc: dictionary)
  681. case .UUID:
  682. return dictionary.isOptional ? Map<String, UUID?>(objc: dictionary) : Map<String, UUID>(objc: dictionary)
  683. case .string:
  684. return dictionary.isOptional ? Map<String, String?>(objc: dictionary) : Map<String, String>(objc: dictionary)
  685. case .data:
  686. return dictionary.isOptional ? Map<String, Data?>(objc: dictionary) : Map<String, Data>(objc: dictionary)
  687. case .date:
  688. return dictionary.isOptional ? Map<String, Date?>(objc: dictionary) : Map<String, Date>(objc: dictionary)
  689. case .any:
  690. return Map<String, AnyRealmValue>(objc: dictionary)
  691. case .linkingObjects:
  692. throwRealmException("Unsupported migration type of 'LinkingObjects' for type 'Map'.")
  693. case .objectId:
  694. return dictionary.isOptional ? Map<String, ObjectId?>(objc: dictionary) : Map<String, ObjectId>(objc: dictionary)
  695. case .object:
  696. return Map<String, DynamicObject?>(objc: dictionary)
  697. }
  698. }
  699. }
  700. /**
  701. An enum type which can be stored on a Realm Object.
  702. Only `@objc` enums backed by an Int can be stored on a Realm object, and the
  703. enum type must explicitly conform to this protocol. For example:
  704. ```
  705. @objc enum MyEnum: Int, RealmEnum {
  706. case first = 1
  707. case second = 2
  708. case third = 7
  709. }
  710. class MyModel: Object {
  711. @objc dynamic enumProperty = MyEnum.first
  712. let optionalEnumProperty = RealmOptional<MyEnum>()
  713. }
  714. ```
  715. */
  716. public protocol RealmEnum: RealmOptionalType, _RealmSchemaDiscoverable {
  717. }
  718. // MARK: - Implementation
  719. /// :nodoc:
  720. public extension RealmEnum where Self: RawRepresentable, Self.RawValue: _RealmSchemaDiscoverable & _ObjcBridgeable {
  721. var _rlmObjcValue: Any { rawValue._rlmObjcValue }
  722. static func _rlmFromObjc(_ value: Any, insideOptional: Bool) -> Self? {
  723. if let value = value as? Self {
  724. return value
  725. }
  726. if let value = value as? RawValue {
  727. return Self(rawValue: value)
  728. }
  729. return nil
  730. }
  731. static func _rlmPopulateProperty(_ prop: RLMProperty) {
  732. RawValue._rlmPopulateProperty(prop)
  733. }
  734. static var _rlmType: PropertyType { RawValue._rlmType }
  735. }
  736. internal func dynamicSet(object: ObjectBase, key: String, value: Any?) {
  737. let bridgedValue: Any?
  738. if let v1 = value, let v2 = v1 as AnyObject as? _ObjcBridgeable {
  739. bridgedValue = v2._rlmObjcValue
  740. } else {
  741. bridgedValue = value
  742. }
  743. if RLMObjectBaseRealm(object) == nil {
  744. object.setValue(bridgedValue, forKey: key)
  745. } else {
  746. RLMDynamicValidatedSet(object, key, bridgedValue)
  747. }
  748. }