Results.swift 16 KB

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