LinkingObjects.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 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. `LinkingObjects` is an auto-updating container type. It represents zero or more objects that are linked to its owning
  22. model object through a property relationship.
  23. `LinkingObjects` can be queried with the same predicates as `List<Element>` and `Results<Element>`.
  24. `LinkingObjects` always reflects the current state of the Realm on the current thread, including during write
  25. transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always
  26. enumerate over the linking objects that were present when the enumeration is begun, even if some of them are deleted or
  27. modified to no longer link to the target object during the enumeration.
  28. `LinkingObjects` can only be used as a property on `Object` models. Properties of this type must be declared as `let`
  29. and cannot be `dynamic`.
  30. */
  31. public struct LinkingObjects<Element: Object> {
  32. /// The type of the objects represented by the linking objects.
  33. public typealias ElementType = Element
  34. // MARK: Properties
  35. /// The Realm which manages the linking objects, or `nil` if the linking objects are unmanaged.
  36. public var realm: Realm? { return rlmResults.isAttached ? Realm(rlmResults.realm) : nil }
  37. /// Indicates if the linking objects are no longer valid.
  38. ///
  39. /// The linking objects become invalid if `invalidate()` is called on the containing `realm` instance.
  40. ///
  41. /// An invalidated linking objects can be accessed, but will always be empty.
  42. public var isInvalidated: Bool { return rlmResults.isInvalidated }
  43. /// The number of linking objects.
  44. public var count: Int { return Int(rlmResults.count) }
  45. // MARK: Initializers
  46. /**
  47. Creates an instance of a `LinkingObjects`. This initializer should only be called when declaring a property on a
  48. Realm model.
  49. - parameter type: The type of the object owning the property the linking objects should refer to.
  50. - parameter propertyName: The property name of the property the linking objects should refer to.
  51. */
  52. public init(fromType _: Element.Type, property propertyName: String) {
  53. self.propertyName = propertyName
  54. }
  55. /// A human-readable description of the objects represented by the linking objects.
  56. public var description: String {
  57. if realm == nil {
  58. var this = self
  59. return withUnsafePointer(to: &this) {
  60. return "LinkingObjects<\(Element.className())> <\($0)> (\n\n)"
  61. }
  62. }
  63. return RLMDescriptionWithMaxDepth("LinkingObjects", rlmResults, RLMDescriptionMaxDepth)
  64. }
  65. // MARK: Index Retrieval
  66. /**
  67. Returns the index of an object in the linking objects, or `nil` if the object is not present.
  68. - parameter object: The object whose index is being queried.
  69. */
  70. public func index(of object: Element) -> Int? {
  71. return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject()))
  72. }
  73. /**
  74. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  75. - parameter predicate: The predicate with which to filter the objects.
  76. */
  77. public func index(matching predicate: NSPredicate) -> Int? {
  78. return notFoundToNil(index: rlmResults.indexOfObject(with: predicate))
  79. }
  80. // MARK: Object Retrieval
  81. /**
  82. Returns the object at the given `index`.
  83. - parameter index: The index.
  84. */
  85. public subscript(index: Int) -> Element {
  86. throwForNegativeIndex(index)
  87. return unsafeBitCast(rlmResults[UInt(index)], to: Element.self)
  88. }
  89. /// Returns the first object in the linking objects, or `nil` if the linking objects are empty.
  90. public var first: Element? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<Element>.self) }
  91. /// Returns the last object in the linking objects, or `nil` if the linking objects are empty.
  92. public var last: Element? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<Element>.self) }
  93. // MARK: KVC
  94. /**
  95. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the linking objects.
  96. - parameter key: The name of the property whose values are desired.
  97. */
  98. public func value(forKey key: String) -> Any? {
  99. return value(forKeyPath: key)
  100. }
  101. /**
  102. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the linking
  103. objects.
  104. - parameter keyPath: The key path to the property whose values are desired.
  105. */
  106. public func value(forKeyPath keyPath: String) -> Any? {
  107. return rlmResults.value(forKeyPath: keyPath)
  108. }
  109. /**
  110. Invokes `setValue(_:forKey:)` on each of the linking objects using the specified `value` and `key`.
  111. - warning: This method may only be called during a write transaction.
  112. - parameter value: The value to set the property to.
  113. - parameter key: The name of the property whose value should be set on each object.
  114. */
  115. public func setValue(_ value: Any?, forKey key: String) {
  116. return rlmResults.setValue(value, forKeyPath: key)
  117. }
  118. // MARK: Filtering
  119. /**
  120. Returns a `Results` containing all objects matching the given predicate in the linking objects.
  121. - parameter predicate: The predicate with which to filter the objects.
  122. */
  123. public func filter(_ predicate: NSPredicate) -> Results<Element> {
  124. return Results(rlmResults.objects(with: predicate))
  125. }
  126. // MARK: Sorting
  127. /**
  128. Returns a `Results` containing all the linking objects, but sorted.
  129. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  130. youngest to oldest based on their `age` property, you might call
  131. `students.sorted(byKeyPath: "age", ascending: true)`.
  132. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  133. floating point, integer, and string types.
  134. - parameter keyPath: The key path to sort by.
  135. - parameter ascending: The direction to sort in.
  136. */
  137. public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
  138. return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
  139. }
  140. /**
  141. Returns a `Results` containing all the linking objects, but sorted.
  142. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  143. floating point, integer, and string types.
  144. - see: `sorted(byKeyPath:ascending:)`
  145. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  146. */
  147. public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
  148. where S.Iterator.Element == SortDescriptor {
  149. return Results(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
  150. }
  151. // MARK: Aggregate Operations
  152. /**
  153. Returns the minimum (lowest) value of the given property among all the linking objects, or `nil` if the linking
  154. objects are empty.
  155. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  156. - parameter property: The name of a property whose minimum value is desired.
  157. */
  158. public func min<T: MinMaxType>(ofProperty property: String) -> T? {
  159. return rlmResults.min(ofProperty: property).map(dynamicBridgeCast)
  160. }
  161. /**
  162. Returns the maximum (highest) value of the given property among all the linking objects, or `nil` if the linking
  163. objects are empty.
  164. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  165. - parameter property: The name of a property whose minimum value is desired.
  166. */
  167. public func max<T: MinMaxType>(ofProperty property: String) -> T? {
  168. return rlmResults.max(ofProperty: property).map(dynamicBridgeCast)
  169. }
  170. /**
  171. Returns the sum of the values of a given property over all the linking objects.
  172. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  173. - parameter property: The name of a property whose values should be summed.
  174. */
  175. public func sum<T: AddableType>(ofProperty property: String) -> T {
  176. return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property))
  177. }
  178. /**
  179. Returns the average value of a given property over all the linking objects, or `nil` if the linking objects are
  180. empty.
  181. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
  182. - parameter property: The name of a property whose average value should be calculated.
  183. */
  184. public func average<T: AddableType>(ofProperty property: String) -> T? {
  185. return rlmResults.average(ofProperty: property).map(dynamicBridgeCast)
  186. }
  187. // MARK: Notifications
  188. /**
  189. Registers a block to be called each time the collection changes.
  190. The block will be asynchronously called with the initial results, and then called again after each write
  191. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  192. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  193. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  194. documentation for more information on the change information supplied and an example of how to use it to update a
  195. `UITableView`.
  196. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  197. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  198. perform blocking work.
  199. If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
  200. run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
  201. notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
  202. This can include the notification with the initial collection.
  203. For example, the following code performs a write transaction immediately after adding the notification block, so
  204. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  205. will reflect the state of the Realm after the write transaction.
  206. ```swift
  207. let results = realm.objects(Dog.self)
  208. print("dogs.count: \(dogs?.count)") // => 0
  209. let token = dogs.observe { changes in
  210. switch changes {
  211. case .initial(let dogs):
  212. // Will print "dogs.count: 1"
  213. print("dogs.count: \(dogs.count)")
  214. break
  215. case .update:
  216. // Will not be hit in this example
  217. break
  218. case .error:
  219. break
  220. }
  221. }
  222. try! realm.write {
  223. let dog = Dog()
  224. dog.name = "Rex"
  225. person.dogs.append(dog)
  226. }
  227. // end of run loop execution context
  228. ```
  229. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  230. updates, call `invalidate()` on the token.
  231. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  232. - parameter queue: The serial dispatch queue to receive notification on. If
  233. `nil`, notifications are delivered to the current thread.
  234. - parameter block: The block to be called whenever a change occurs.
  235. - returns: A token which must be held for as long as you want updates to be delivered.
  236. */
  237. public func observe(on queue: DispatchQueue? = nil,
  238. _ block: @escaping (RealmCollectionChange<LinkingObjects>) -> Void) -> NotificationToken {
  239. return rlmResults.addNotificationBlock(wrapObserveBlock(block), queue: queue)
  240. }
  241. // MARK: Frozen Objects
  242. /// Returns if this collection is frozen.
  243. public var isFrozen: Bool { return self.rlmResults.isFrozen }
  244. /**
  245. Returns a frozen (immutable) snapshot of this collection.
  246. The frozen copy is an immutable collection which contains the same data as this collection
  247. currently contains, but will not update when writes are made to the containing Realm. Unlike
  248. live collections, frozen collections can be accessed from any thread.
  249. - warning: This method cannot be called during a write transaction, or when the containing
  250. Realm is read-only.
  251. - warning: Holding onto a frozen collection for an extended period while performing write
  252. transaction on the Realm may result in the Realm file growing to large sizes. See
  253. `Realm.Configuration.maximumNumberOfActiveVersions` for more information.
  254. */
  255. public func freeze() -> LinkingObjects {
  256. return LinkingObjects(propertyName: propertyName, handle: handle?.freeze())
  257. }
  258. // MARK: Implementation
  259. private init(propertyName: String, handle: RLMLinkingObjectsHandle?) {
  260. self.propertyName = propertyName
  261. self.handle = handle
  262. }
  263. internal init(objc: RLMResults<AnyObject>) {
  264. self.propertyName = ""
  265. self.handle = RLMLinkingObjectsHandle(linkingObjects: objc)
  266. }
  267. internal var rlmResults: RLMResults<AnyObject> {
  268. return handle?.results ?? RLMResults<AnyObject>.emptyDetached()
  269. }
  270. internal var propertyName: String
  271. internal var handle: RLMLinkingObjectsHandle?
  272. }
  273. extension LinkingObjects: RealmCollection {
  274. // MARK: Sequence Support
  275. /// Returns an iterator that yields successive elements in the linking objects.
  276. public func makeIterator() -> RLMIterator<Element> {
  277. return RLMIterator(collection: rlmResults)
  278. }
  279. /// :nodoc:
  280. // swiftlint:disable:next identifier_name
  281. public func _asNSFastEnumerator() -> Any {
  282. return rlmResults
  283. }
  284. // MARK: Collection Support
  285. /// The position of the first element in a non-empty collection.
  286. /// Identical to endIndex in an empty collection.
  287. public var startIndex: Int { return 0 }
  288. /// The collection's "past the end" position.
  289. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
  290. /// zero or more applications of successor().
  291. public var endIndex: Int { return count }
  292. public func index(after: Int) -> Int {
  293. return after + 1
  294. }
  295. public func index(before: Int) -> Int {
  296. return before - 1
  297. }
  298. /// :nodoc:
  299. // swiftlint:disable:next identifier_name
  300. public func _observe(_ queue: DispatchQueue?,
  301. _ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void)
  302. -> NotificationToken {
  303. return rlmResults.addNotificationBlock(wrapObserveBlock(block), queue: queue)
  304. }
  305. }
  306. // MARK: AssistedObjectiveCBridgeable
  307. extension LinkingObjects: AssistedObjectiveCBridgeable {
  308. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> LinkingObjects {
  309. guard let object = objectiveCValue as? RLMResults<Element> else { preconditionFailure() }
  310. return LinkingObjects<Element>(objc: object as! RLMResults<AnyObject>)
  311. }
  312. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  313. return (objectiveCValue: handle!.results, metadata: nil)
  314. }
  315. }