LinkingObjects.swift 18 KB

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