RealmKeyedCollection.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2021 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. /**
  21. A homogenous key-value collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
  22. */
  23. public protocol RealmKeyedCollection: Sequence, ThreadConfined, CustomStringConvertible {
  24. /// The type of key associated with this collection
  25. associatedtype Key: _MapKey
  26. /// The type of value associated with this collection.
  27. associatedtype Value: RealmCollectionValue
  28. // MARK: Properties
  29. /// The Realm which manages the map, or `nil` if the map is unmanaged.
  30. var realm: Realm? { get }
  31. /// Indicates if the map can no longer be accessed.
  32. var isInvalidated: Bool { get }
  33. /// Returns the number of key-value pairs in this map.
  34. var count: Int { get }
  35. /// A human-readable description of the objects contained in the Map.
  36. var description: String { get }
  37. // MARK: Mutation
  38. /**
  39. Updates the value stored in the dictionary for the given key, or adds a new key-value pair if the key does not exist.
  40. - Note:If the value being added to the dictionary is an unmanaged object and the dictionary is managed
  41. then that unmanaged object will be added to the Realm.
  42. - warning: This method may only be called during a write transaction.
  43. - parameter value: a value's key path predicate.
  44. - parameter forKey: The direction to sort in.
  45. */
  46. func updateValue(_ value: Value, forKey key: Key)
  47. /**
  48. Removes the given key and its associated object, only if the key exists in the dictionary. If the key does not
  49. exist, the dictionary will not be modified.
  50. - warning: This method may only be called during a write transaction.
  51. */
  52. func removeObject(for key: Key)
  53. /**
  54. Removes all objects from the dictionary. The objects are not removed from the Realm that manages them.
  55. - warning: This method may only be called during a write transaction.
  56. */
  57. func removeAll()
  58. /**
  59. Returns the value for a given key, or sets a value for a key should the subscript be used for an assign.
  60. - Note:If the value being added to the dictionary is an unmanaged object and the dictionary is managed
  61. then that unmanaged object will be added to the Realm.
  62. - Note:If the value being assigned for a key is `nil` then that key will be removed from the dictionary.
  63. - warning: This method may only be called during a write transaction.
  64. - parameter key: The key.
  65. */
  66. subscript(key: Key) -> Value? { get set }
  67. // MARK: KVC
  68. /**
  69. Returns a type of `Value` for a specified key if it exists in the map.
  70. Note that when using key-value coding, the key must be a string.
  71. - parameter key: The key to the property whose values are desired.
  72. */
  73. func value(forKey key: String) -> AnyObject?
  74. /**
  75. Returns a type of `Value` for a specified key if it exists in the map.
  76. - parameter keyPath: The key to the property whose values are desired.
  77. */
  78. func value(forKeyPath keyPath: String) -> AnyObject?
  79. /**
  80. Adds a given key-value pair to the dictionary or updates a given key should it already exist.
  81. - warning: This method can only be called during a write transaction.
  82. - parameter value: The object value.
  83. - parameter key: The name of the property whose value should be set on each object.
  84. */
  85. func setValue(_ value: Any?, forKey key: String)
  86. // MARK: Filtering
  87. /**
  88. Returns a `Results` containing all matching values in the dictionary with the given predicate.
  89. - Note: This will return the values in the dictionary, and not the key-value pairs.
  90. - parameter predicate: The predicate with which to filter the values.
  91. */
  92. func filter(_ predicate: NSPredicate) -> Results<Value>
  93. /**
  94. Returns a Boolean value indicating whether the Map contains the key-value pair
  95. satisfies the given predicate
  96. - parameter where: a closure that test if any key-pair of the given map represents the match.
  97. */
  98. func contains(where predicate: @escaping (_ key: Key, _ value: Value) -> Bool) -> Bool
  99. // MARK: Sorting
  100. /**
  101. Returns a `Results` containing the objects in the dictionary, but sorted.
  102. Objects are sorted based on their values. For example, to sort a dictionary of `Date`s from
  103. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  104. - parameter ascending: The direction to sort in.
  105. */
  106. func sorted(ascending: Bool) -> Results<Value>
  107. /**
  108. Returns a `Results` containing the objects in the dictionary, but sorted.
  109. Objects are sorted based on the values of the given key path. For example, to sort a dictionary of `Student`s from
  110. youngest to oldest based on their `age` property, you might call
  111. `students.sorted(byKeyPath: "age", ascending: true)`.
  112. - warning: Dictionaries may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  113. floating point, integer, and string types.
  114. - parameter keyPath: The key path to sort by.
  115. - parameter ascending: The direction to sort in.
  116. */
  117. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Value>
  118. /**
  119. Returns a `Results` containing the objects in the dictionary, but sorted.
  120. - warning: Dictionaries may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  121. floating point, integer, and string types.
  122. - see: `sorted(byKeyPath:ascending:)`
  123. */
  124. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Value>
  125. where S.Iterator.Element == SortDescriptor
  126. /// Returns all of the keys in this dictionary.
  127. var keys: [Key] { get }
  128. /// Returns all of the values in the dictionary.
  129. var values: [Value] { get }
  130. // MARK: Aggregate Operations
  131. /**
  132. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  133. dictionary is empty.
  134. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  135. - parameter property: The name of a property whose minimum value is desired.
  136. */
  137. func min<T: MinMaxType>(ofProperty property: String) -> T?
  138. /**
  139. Returns the maximum (highest) value of the given property among all the objects in the dictionary, or `nil` if the
  140. dictionary is empty.
  141. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  142. - parameter property: The name of a property whose minimum value is desired.
  143. */
  144. func max<T: MinMaxType>(ofProperty property: String) -> T?
  145. /**
  146. Returns the sum of the given property for objects in the dictionary, or `nil` if the dictionary is empty.
  147. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
  148. - parameter property: The name of a property conforming to `AddableType` to calculate sum on.
  149. */
  150. func sum<T: AddableType>(ofProperty property: String) -> T
  151. /**
  152. Returns the average value of a given property over all the objects in the dictionary, or `nil` if
  153. the dictionary is empty.
  154. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  155. - parameter property: The name of a property whose values should be summed.
  156. */
  157. func average<T: AddableType>(ofProperty property: String) -> T?
  158. // MARK: Notifications
  159. /**
  160. Registers a block to be called each time the dictionary changes.
  161. The block will be asynchronously called with the initial dictionary, and then called again after each write
  162. transaction which changes either any of the keys or values in the dictionary.
  163. The `change` parameter that is passed to the block reports, in the form of keys within the dictionary, which of
  164. the key-value pairs were added, removed, or modified during each write transaction.
  165. At the time when the block is called, the dictionary will be fully evaluated and up-to-date, and as long as you do
  166. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  167. perform blocking work.
  168. If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
  169. run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
  170. notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
  171. This can include the notification with the initial collection.
  172. For example, the following code performs a write transaction immediately after adding the notification block, so
  173. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  174. will reflect the state of the Realm after the write transaction.
  175. ```swift
  176. let myStringMap = myObject.stringMap
  177. print("myStringMap.count: \(myStringMap?.count)") // => 0
  178. let token = myStringMap.observe { changes in
  179. switch changes {
  180. case .initial(let myStringMap):
  181. // Will print "myStringMap.count: 1"
  182. print("myStringMap.count: \(myStringMap.count)")
  183. print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
  184. break
  185. case .update:
  186. // Will not be hit in this example
  187. break
  188. case .error:
  189. break
  190. }
  191. }
  192. try! realm.write {
  193. myStringMap["nameOfDog"] = "Rex"
  194. }
  195. // end of run loop execution context
  196. ```
  197. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  198. updates, call `invalidate()` on the token.
  199. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  200. - parameter queue: The serial dispatch queue to receive notification on. If
  201. `nil`, notifications are delivered to the current thread.
  202. - parameter block: The block to be called whenever a change occurs.
  203. - returns: A token which must be held for as long as you want updates to be delivered.
  204. */
  205. func observe(on queue: DispatchQueue?,
  206. _ block: @escaping (RealmMapChange<Self>) -> Void)
  207. -> NotificationToken
  208. /**
  209. Registers a block to be called each time the dictionary changes.
  210. The block will be asynchronously called with the initial dictionary, and then called again after each write
  211. transaction which changes either any of the keys or values in the dictionary.
  212. The `change` parameter that is passed to the block reports, in the form of keys within the dictionary, which of
  213. the key-value pairs were added, removed, or modified during each write transaction.
  214. At the time when the block is called, the dictionary will be fully evaluated and up-to-date, and as long as you do
  215. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  216. perform blocking work.
  217. If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
  218. run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
  219. notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
  220. This can include the notification with the initial collection.
  221. For example, the following code performs a write transaction immediately after adding the notification block, so
  222. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  223. will reflect the state of the Realm after the write transaction.
  224. ```swift
  225. let myStringMap = myObject.stringMap
  226. print("myStringMap.count: \(myStringMap?.count)") // => 0
  227. let token = myStringMap.observe { changes in
  228. switch changes {
  229. case .initial(let myStringMap):
  230. // Will print "myStringMap.count: 1"
  231. print("myStringMap.count: \(myStringMap.count)")
  232. print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
  233. break
  234. case .update:
  235. // Will not be hit in this example
  236. break
  237. case .error:
  238. break
  239. }
  240. }
  241. try! realm.write {
  242. myStringMap["nameOfDog"] = "Rex"
  243. }
  244. // end of run loop execution context
  245. ```
  246. If no key paths are given, the block will be executed on any insertion,
  247. modification, or deletion for all object properties and the properties of
  248. any nested, linked objects. If a key path or key paths are provided,
  249. then the block will be called for changes which occur only on the
  250. provided key paths. For example, if:
  251. ```swift
  252. class Dog: Object {
  253. @Persisted var name: String
  254. @Persisted var age: Int
  255. @Persisted var toys: List<Toy>
  256. }
  257. // ...
  258. let dogs = myObject.mapOfDogs
  259. let token = dogs.observe(keyPaths: ["name"]) { changes in
  260. switch changes {
  261. case .initial(let dogs):
  262. // ...
  263. case .update:
  264. // This case is hit:
  265. // - after the token is intialized
  266. // - when the name property of an object in the
  267. // collection is modified
  268. // - when an element is inserted or removed
  269. // from the collection.
  270. // This block is not triggered:
  271. // - when a value other than name is modified on
  272. // one of the elements.
  273. case .error:
  274. // ...
  275. }
  276. }
  277. // end of run loop execution context
  278. ```
  279. - If the observed key path were `["toys.brand"]`, then any insertion or
  280. deletion to the `toys` list on any of the collection's elements would trigger the block.
  281. Changes to the `brand` value on any `Toy` that is linked to a `Dog` in this
  282. collection will trigger the block. Changes to a value other than `brand` on any `Toy` that
  283. is linked to a `Dog` in this collection would not trigger the block.
  284. Any insertion or removal to the `Dog` type collection being observed
  285. would also trigger a notification.
  286. - If the above example observed the `["toys"]` key path, then any insertion,
  287. deletion, or modification to the `toys` list for any element in the collection
  288. would trigger the block.
  289. Changes to any value on any `Toy` that is linked to a `Dog` in this collection
  290. would *not* trigger the block.
  291. Any insertion or removal to the `Dog` type collection being observed
  292. would still trigger a notification.
  293. - note: Multiple notification tokens on the same object which filter for
  294. separate key paths *do not* filter exclusively. If one key path
  295. change is satisfied for one notification token, then all notification
  296. token blocks for that object will execute.
  297. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  298. updates, call `invalidate()` on the token.
  299. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  300. - parameter keyPaths: Only properties contained in the key paths array will trigger
  301. the block when they are modified. If `nil`, notifications
  302. will be delivered for any property change on the object.
  303. String key paths which do not correspond to a valid a property
  304. will throw an exception.
  305. See description above for more detail on linked properties.
  306. - note: The keyPaths parameter refers to object properties of the collection type and
  307. *does not* refer to particular key/value pairs within the collection.
  308. - parameter queue: The serial dispatch queue to receive notification on. If
  309. `nil`, notifications are delivered to the current thread.
  310. - parameter block: The block to be called whenever a change occurs.
  311. - returns: A token which must be held for as long as you want updates to be delivered.
  312. */
  313. func observe(keyPaths: [String]?,
  314. on queue: DispatchQueue?,
  315. _ block: @escaping (RealmMapChange<Self>) -> Void) -> NotificationToken
  316. // MARK: Frozen Objects
  317. /// Returns if this collection is frozen
  318. var isFrozen: Bool { get }
  319. /**
  320. Returns a frozen (immutable) snapshot of this collection.
  321. The frozen copy is an immutable collection which contains the same data as this collection
  322. currently contains, but will not update when writes are made to the containing Realm. Unlike
  323. live collections, frozen collections can be accessed from any thread.
  324. - warning: This method cannot be called during a write transaction, or when the containing
  325. Realm is read-only.
  326. - warning: Holding onto a frozen collection for an extended period while performing write
  327. transaction on the Realm may result in the Realm file growing to large sizes. See
  328. `Realm.Configuration.maximumNumberOfActiveVersions` for more information.
  329. */
  330. func freeze() -> Self
  331. /**
  332. Returns a live (mutable) version of this frozen collection.
  333. This method resolves a reference to a live copy of the same frozen collection.
  334. If called on a live collection, will return itself.
  335. */
  336. func thaw() -> Self?
  337. }
  338. /**
  339. Protocol for RealmKeyedCollections where the Value is of an Object type that
  340. enables aggregatable operations.
  341. */
  342. public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: ObjectBase, Value.Wrapped: RealmCollectionValue {
  343. /**
  344. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  345. collection is empty.
  346. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  347. - parameter keyPath: The keyPath of a property whose minimum value is desired.
  348. */
  349. func min<T: MinMaxType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
  350. min(ofProperty: _name(for: keyPath))
  351. }
  352. /**
  353. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  354. collection is empty.
  355. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  356. - parameter keyPath: The keyPath of a property whose minimum value is desired.
  357. */
  358. func max<T: MinMaxType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
  359. max(ofProperty: _name(for: keyPath))
  360. }
  361. /**
  362. Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
  363. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
  364. - parameter keyPath: The keyPath of a property conforming to `AddableType` to calculate sum on.
  365. */
  366. func sum<T: AddableType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T {
  367. sum(ofProperty: _name(for: keyPath))
  368. }
  369. /**
  370. Returns the average value of a given property over all the objects in the collection, or `nil` if
  371. the collection is empty.
  372. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  373. - parameter keyPath: The keyPath of a property whose values should be summed.
  374. */
  375. func average<T: AddableType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
  376. average(ofProperty: _name(for: keyPath))
  377. }
  378. }
  379. // MARK: Sortable
  380. /**
  381. Protocol for RealmKeyedCollections where the Value is of an Object type that
  382. enables sortable operations.
  383. */
  384. public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: ObjectBase, Value.Wrapped: RealmCollectionValue {
  385. /**
  386. Returns a `Results` containing the objects in the collection, but sorted.
  387. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  388. youngest to oldest based on their `age` property, you might call
  389. `students.sorted(byKeyPath: "age", ascending: true)`.
  390. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  391. floating point, integer, and string types.
  392. - parameter keyPath: The key path to sort by.
  393. - parameter ascending: The direction to sort in.
  394. */
  395. func sorted<T: Comparable>(by keyPath: KeyPath<Value.Wrapped, T>, ascending: Bool) -> Results<Value> {
  396. sorted(byKeyPath: _name(for: keyPath), ascending: ascending)
  397. }
  398. }
  399. public extension RealmKeyedCollection where Value: MinMaxType {
  400. /**
  401. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  402. */
  403. func min() -> Value? {
  404. return min(ofProperty: "self")
  405. }
  406. /**
  407. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  408. */
  409. func max() -> Value? {
  410. return max(ofProperty: "self")
  411. }
  412. }
  413. public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: MinMaxType {
  414. /**
  415. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  416. */
  417. func min() -> Value.Wrapped? {
  418. return min(ofProperty: "self")
  419. }
  420. /**
  421. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  422. */
  423. func max() -> Value.Wrapped? {
  424. return max(ofProperty: "self")
  425. }
  426. }
  427. public extension RealmKeyedCollection where Value: AddableType {
  428. /**
  429. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  430. */
  431. func sum() -> Value {
  432. return sum(ofProperty: "self")
  433. }
  434. /**
  435. Returns the average of all of the values in the collection.
  436. */
  437. func average<T: AddableType>() -> T? {
  438. return average(ofProperty: "self")
  439. }
  440. }
  441. public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: AddableType {
  442. /**
  443. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  444. */
  445. func sum() -> Value.Wrapped {
  446. return sum(ofProperty: "self")
  447. }
  448. /**
  449. Returns the average of all of the values in the collection.
  450. */
  451. func average<T: AddableType>() -> T? {
  452. return average(ofProperty: "self")
  453. }
  454. }
  455. public extension RealmKeyedCollection where Value: Comparable {
  456. /**
  457. Returns a `Results` containing the objects in the collection, but sorted.
  458. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  459. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  460. - parameter ascending: The direction to sort in.
  461. */
  462. func sorted(ascending: Bool = true) -> Results<Value> {
  463. return sorted(byKeyPath: "self", ascending: ascending)
  464. }
  465. }
  466. public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: Comparable {
  467. /**
  468. Returns a `Results` containing the objects in the collection, but sorted.
  469. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  470. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  471. - parameter ascending: The direction to sort in.
  472. */
  473. func sorted(ascending: Bool = true) -> Results<Value> {
  474. return sorted(byKeyPath: "self", ascending: ascending)
  475. }
  476. }