Results.swift 16 KB

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