LinkingObjects.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. /**
  81. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  82. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  83. */
  84. public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  85. return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat,
  86. argumentArray: unwrapOptionals(in: args))))
  87. }
  88. // MARK: Object Retrieval
  89. /**
  90. Returns the object at the given `index`.
  91. - parameter index: The index.
  92. */
  93. public subscript(index: Int) -> Element {
  94. throwForNegativeIndex(index)
  95. return unsafeBitCast(rlmResults[UInt(index)], to: Element.self)
  96. }
  97. /// Returns the first object in the linking objects, or `nil` if the linking objects are empty.
  98. public var first: Element? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<Element>.self) }
  99. /// Returns the last object in the linking objects, or `nil` if the linking objects are empty.
  100. public var last: Element? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<Element>.self) }
  101. // MARK: KVC
  102. /**
  103. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the linking objects.
  104. - parameter key: The name of the property whose values are desired.
  105. */
  106. public func value(forKey key: String) -> Any? {
  107. return value(forKeyPath: key)
  108. }
  109. /**
  110. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the linking
  111. objects.
  112. - parameter keyPath: The key path to the property whose values are desired.
  113. */
  114. public func value(forKeyPath keyPath: String) -> Any? {
  115. return rlmResults.value(forKeyPath: keyPath)
  116. }
  117. /**
  118. Invokes `setValue(_:forKey:)` on each of the linking objects using the specified `value` and `key`.
  119. - warning: This method may only be called during a write transaction.
  120. - parameter value: The value to set the property to.
  121. - parameter key: The name of the property whose value should be set on each object.
  122. */
  123. public func setValue(_ value: Any?, forKey key: String) {
  124. return rlmResults.setValue(value, forKeyPath: key)
  125. }
  126. // MARK: Filtering
  127. /**
  128. Returns a `Results` containing all objects matching the given predicate in the linking objects.
  129. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  130. */
  131. public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
  132. return Results(rlmResults.objects(with: NSPredicate(format: predicateFormat,
  133. argumentArray: unwrapOptionals(in: args))))
  134. }
  135. /**
  136. Returns a `Results` containing all objects matching the given predicate in the linking objects.
  137. - parameter predicate: The predicate with which to filter the objects.
  138. */
  139. public func filter(_ predicate: NSPredicate) -> Results<Element> {
  140. return Results(rlmResults.objects(with: predicate))
  141. }
  142. // MARK: Sorting
  143. /**
  144. Returns a `Results` containing all the linking objects, but sorted.
  145. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  146. youngest to oldest based on their `age` property, you might call
  147. `students.sorted(byKeyPath: "age", ascending: true)`.
  148. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  149. floating point, integer, and string types.
  150. - parameter keyPath: The key path to sort by.
  151. - parameter ascending: The direction to sort in.
  152. */
  153. public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
  154. return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
  155. }
  156. /**
  157. Returns a `Results` containing all the linking objects, but sorted.
  158. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  159. floating point, integer, and string types.
  160. - see: `sorted(byKeyPath:ascending:)`
  161. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  162. */
  163. public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
  164. where S.Iterator.Element == SortDescriptor {
  165. return Results(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
  166. }
  167. // MARK: Aggregate Operations
  168. /**
  169. Returns the minimum (lowest) value of the given property among all the linking objects, or `nil` if the linking
  170. objects are empty.
  171. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  172. - parameter property: The name of a property whose minimum value is desired.
  173. */
  174. public func min<T: MinMaxType>(ofProperty property: String) -> T? {
  175. return rlmResults.min(ofProperty: property).map(dynamicBridgeCast)
  176. }
  177. /**
  178. Returns the maximum (highest) value of the given property among all the linking objects, or `nil` if the linking
  179. objects are empty.
  180. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  181. - parameter property: The name of a property whose minimum value is desired.
  182. */
  183. public func max<T: MinMaxType>(ofProperty property: String) -> T? {
  184. return rlmResults.max(ofProperty: property).map(dynamicBridgeCast)
  185. }
  186. /**
  187. Returns the sum of the values of a given property over all the linking objects.
  188. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  189. - parameter property: The name of a property whose values should be summed.
  190. */
  191. public func sum<T: AddableType>(ofProperty property: String) -> T {
  192. return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property))
  193. }
  194. /**
  195. Returns the average value of a given property over all the linking objects, or `nil` if the linking objects are
  196. empty.
  197. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
  198. - parameter property: The name of a property whose average value should be calculated.
  199. */
  200. public func average<T: AddableType>(ofProperty property: String) -> T? {
  201. return rlmResults.average(ofProperty: property).map(dynamicBridgeCast)
  202. }
  203. // MARK: Notifications
  204. /**
  205. Registers a block to be called each time the collection changes.
  206. The block will be asynchronously called with the initial results, and then called again after each write
  207. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  208. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  209. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  210. documentation for more information on the change information supplied and an example of how to use it to update a
  211. `UITableView`.
  212. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  213. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  214. perform blocking work.
  215. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  216. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  217. single notification. This can include the notification with the initial collection.
  218. For example, the following code performs a write transaction immediately after adding the notification block, so
  219. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  220. will reflect the state of the Realm after the write transaction.
  221. ```swift
  222. let results = realm.objects(Dog.self)
  223. print("dogs.count: \(dogs?.count)") // => 0
  224. let token = dogs.observe { changes in
  225. switch changes {
  226. case .initial(let dogs):
  227. // Will print "dogs.count: 1"
  228. print("dogs.count: \(dogs.count)")
  229. break
  230. case .update:
  231. // Will not be hit in this example
  232. break
  233. case .error:
  234. break
  235. }
  236. }
  237. try! realm.write {
  238. let dog = Dog()
  239. dog.name = "Rex"
  240. person.dogs.append(dog)
  241. }
  242. // end of run loop execution context
  243. ```
  244. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  245. updates, call `invalidate()` on the token.
  246. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  247. - parameter block: The block to be called whenever a change occurs.
  248. - returns: A token which must be held for as long as you want updates to be delivered.
  249. */
  250. public func observe(_ block: @escaping (RealmCollectionChange<LinkingObjects>) -> Void) -> NotificationToken {
  251. return rlmResults.addNotificationBlock { _, change, error in
  252. block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
  253. }
  254. }
  255. internal var rlmResults: RLMResults<AnyObject> {
  256. return handle?.results ?? RLMResults<AnyObject>.emptyDetached()
  257. }
  258. internal var propertyName: String
  259. internal var handle: RLMLinkingObjectsHandle?
  260. }
  261. extension LinkingObjects: RealmCollection {
  262. // MARK: Sequence Support
  263. /// Returns an iterator that yields successive elements in the linking objects.
  264. public func makeIterator() -> RLMIterator<Element> {
  265. return RLMIterator(collection: rlmResults)
  266. }
  267. /// :nodoc:
  268. // swiftlint:disable:next identifier_name
  269. public func _asNSFastEnumerator() -> Any {
  270. return rlmResults
  271. }
  272. // MARK: Collection Support
  273. /// The position of the first element in a non-empty collection.
  274. /// Identical to endIndex in an empty collection.
  275. public var startIndex: Int { return 0 }
  276. /// The collection's "past the end" position.
  277. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
  278. /// zero or more applications of successor().
  279. public var endIndex: Int { return count }
  280. public func index(after: Int) -> Int {
  281. return after + 1
  282. }
  283. public func index(before: Int) -> Int {
  284. return before - 1
  285. }
  286. /// :nodoc:
  287. public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) ->
  288. NotificationToken {
  289. let anyCollection = AnyRealmCollection(self)
  290. return rlmResults.addNotificationBlock { _, change, error in
  291. block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
  292. }
  293. }
  294. }
  295. // MARK: AssistedObjectiveCBridgeable
  296. extension LinkingObjects: AssistedObjectiveCBridgeable {
  297. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> LinkingObjects {
  298. guard let object = objectiveCValue as? RLMObjectBase else { preconditionFailure() }
  299. guard let propertyName = metadata as? String else { preconditionFailure() }
  300. var ret = LinkingObjects(fromType: Element.self, property: propertyName)
  301. ret.handle = RLMLinkingObjectsHandle(object: object, property: RLMObjectBaseObjectSchema(object)![propertyName]!)
  302. return ret
  303. }
  304. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  305. return (objectiveCValue: handle!.parent, metadata: handle!.property.name)
  306. }
  307. }