Results.swift 16 KB

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