RLMResults.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 <Realm/RLMCollection.h>
  19. NS_ASSUME_NONNULL_BEGIN
  20. @class RLMObject;
  21. /**
  22. `RLMResults` is an auto-updating container type in Realm returned from object
  23. queries. It represents the results of the query in the form of a collection of objects.
  24. `RLMResults` can be queried using the same predicates as `RLMObject` and `RLMArray`,
  25. and you can chain queries to further filter results.
  26. `RLMResults` always reflect the current state of the Realm on the current thread,
  27. including during write transactions on the current thread. The one exception to
  28. this is when using `for...in` fast enumeration, which will always enumerate
  29. over the objects which matched the query when the enumeration is begun, even if
  30. some of them are deleted or modified to be excluded by the filter during the
  31. enumeration.
  32. `RLMResults` are lazily evaluated the first time they are accessed; they only
  33. run queries when the result of the query is requested. This means that
  34. chaining several temporary `RLMResults` to sort and filter your data does not
  35. perform any extra work processing the intermediate state.
  36. Once the results have been evaluated or a notification block has been added,
  37. the results are eagerly kept up-to-date, with the work done to keep them
  38. up-to-date done on a background thread whenever possible.
  39. `RLMResults` cannot be directly instantiated.
  40. */
  41. @interface RLMResults<RLMObjectType> : NSObject<RLMCollection, NSFastEnumeration>
  42. #pragma mark - Properties
  43. /**
  44. The number of objects in the results collection.
  45. */
  46. @property (nonatomic, readonly, assign) NSUInteger count;
  47. /**
  48. The type of the objects in the results collection.
  49. */
  50. @property (nonatomic, readonly, assign) RLMPropertyType type;
  51. /**
  52. Indicates whether the objects in the collection can be `nil`.
  53. */
  54. @property (nonatomic, readwrite, getter = isOptional) BOOL optional;
  55. /**
  56. The class name of the objects contained in the results collection.
  57. Will be `nil` if `type` is not RLMPropertyTypeObject.
  58. */
  59. @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
  60. /**
  61. The Realm which manages this results collection.
  62. */
  63. @property (nonatomic, readonly) RLMRealm *realm;
  64. /**
  65. Indicates if the results collection is no longer valid.
  66. The results collection becomes invalid if `invalidate` is called on the containing `realm`.
  67. An invalidated results collection can be accessed, but will always be empty.
  68. */
  69. @property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
  70. #pragma mark - Accessing Objects from an RLMResults
  71. /**
  72. Returns the object at the index specified.
  73. @param index The index to look up.
  74. @return An object of the type contained in the results collection.
  75. */
  76. - (RLMObjectType)objectAtIndex:(NSUInteger)index;
  77. /**
  78. Returns the first object in the results collection.
  79. Returns `nil` if called on an empty results collection.
  80. @return An object of the type contained in the results collection.
  81. */
  82. - (nullable RLMObjectType)firstObject;
  83. /**
  84. Returns the last object in the results collection.
  85. Returns `nil` if called on an empty results collection.
  86. @return An object of the type contained in the results collection.
  87. */
  88. - (nullable RLMObjectType)lastObject;
  89. #pragma mark - Querying Results
  90. /**
  91. Returns the index of an object in the results collection.
  92. Returns `NSNotFound` if the object is not found in the results collection.
  93. @param object An object (of the same type as returned from the `objectClassName` selector).
  94. */
  95. - (NSUInteger)indexOfObject:(RLMObjectType)object;
  96. /**
  97. Returns the index of the first object in the results collection matching the predicate.
  98. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  99. @return The index of the object, or `NSNotFound` if the object is not found in the results collection.
  100. */
  101. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
  102. /// :nodoc:
  103. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
  104. /**
  105. Returns the index of the first object in the results collection matching the predicate.
  106. @param predicate The predicate with which to filter the objects.
  107. @return The index of the object, or `NSNotFound` if the object is not found in the results collection.
  108. */
  109. - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
  110. /**
  111. Returns all the objects matching the given predicate in the results collection.
  112. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  113. @return An `RLMResults` of objects that match the given predicate.
  114. */
  115. - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat, ...;
  116. /// :nodoc:
  117. - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
  118. /**
  119. Returns all the objects matching the given predicate in the results collection.
  120. @param predicate The predicate with which to filter the objects.
  121. @return An `RLMResults` of objects that match the given predicate.
  122. */
  123. - (RLMResults<RLMObjectType> *)objectsWithPredicate:(NSPredicate *)predicate;
  124. /**
  125. Returns a sorted `RLMResults` from an existing results collection.
  126. @param keyPath The key path to sort by.
  127. @param ascending The direction to sort in.
  128. @return An `RLMResults` sorted by the specified key path.
  129. */
  130. - (RLMResults<RLMObjectType> *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
  131. /**
  132. Returns a sorted `RLMResults` from an existing results collection.
  133. @param properties An array of `RLMSortDescriptor`s to sort by.
  134. @return An `RLMResults` sorted by the specified properties.
  135. */
  136. - (RLMResults<RLMObjectType> *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
  137. /**
  138. Returns a distinct `RLMResults` from an existing results collection.
  139. @param keyPaths The key paths used produce distinct results
  140. @return An `RLMResults` made distinct based on the specified key paths
  141. */
  142. - (RLMResults<RLMObjectType> *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths;
  143. #pragma mark - Notifications
  144. /**
  145. Registers a block to be called each time the results collection changes.
  146. The block will be asynchronously called with the initial results collection,
  147. and then called again after each write transaction which changes either any
  148. of the objects in the results, or which objects are in the results.
  149. The `change` parameter will be `nil` the first time the block is called.
  150. For each call after that, it will contain information about
  151. which rows in the results collection were added, removed or modified. If a
  152. write transaction did not modify any objects in the results collection,
  153. the block is not called at all. See the `RLMCollectionChange` documentation for
  154. information on how the changes are reported and an example of updating a
  155. `UITableView`.
  156. If an error occurs the block will be called with `nil` for the results
  157. parameter and a non-`nil` error. Currently the only errors that can occur are
  158. when opening the Realm on the background worker thread.
  159. At the time when the block is called, the `RLMResults` object will be fully
  160. evaluated and up-to-date, and as long as you do not perform a write transaction
  161. on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will
  162. never perform blocking work.
  163. Notifications are delivered via the standard run loop, and so can't be
  164. delivered while the run loop is blocked by other activity. When
  165. notifications can't be delivered instantly, multiple notifications may be
  166. coalesced into a single notification. This can include the notification
  167. with the initial results. For example, the following code performs a write
  168. transaction immediately after adding the notification block, so there is no
  169. opportunity for the initial notification to be delivered first. As a
  170. result, the initial notification will reflect the state of the Realm after
  171. the write transaction.
  172. RLMResults<Dog *> *results = [Dog allObjects];
  173. NSLog(@"dogs.count: %zu", dogs.count); // => 0
  174. self.token = [results addNotificationBlock:^(RLMResults *dogs,
  175. RLMCollectionChange *changes,
  176. NSError *error) {
  177. // Only fired once for the example
  178. NSLog(@"dogs.count: %zu", dogs.count); // => 1
  179. }];
  180. [realm transactionWithBlock:^{
  181. Dog *dog = [[Dog alloc] init];
  182. dog.name = @"Rex";
  183. [realm addObject:dog];
  184. }];
  185. // end of run loop execution context
  186. You must retain the returned token for as long as you want updates to continue
  187. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  188. @warning This method cannot be called during a write transaction, or when the
  189. containing Realm is read-only.
  190. @param block The block to be called whenever a change occurs.
  191. @return A token which must be held for as long as you want updates to be delivered.
  192. */
  193. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults<RLMObjectType> *_Nullable results,
  194. RLMCollectionChange *_Nullable change,
  195. NSError *_Nullable error))block
  196. __attribute__((warn_unused_result));
  197. /**
  198. Registers a block to be called each time the results collection changes.
  199. The block will be asynchronously called with the initial results collection,
  200. and then called again after each write transaction which changes either any
  201. of the objects in the results, or which objects are in the results.
  202. The `change` parameter will be `nil` the first time the block is called.
  203. For each call after that, it will contain information about
  204. which rows in the results collection were added, removed or modified. If a
  205. write transaction did not modify any objects in the results collection,
  206. the block is not called at all. See the `RLMCollectionChange` documentation for
  207. information on how the changes are reported and an example of updating a
  208. `UITableView`.
  209. If an error occurs the block will be called with `nil` for the results
  210. parameter and a non-`nil` error. Currently the only errors that can occur are
  211. when opening the Realm on the background worker thread.
  212. At the time when the block is called, the `RLMResults` object will be fully
  213. evaluated and up-to-date, and as long as you do not perform a write transaction
  214. on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will
  215. never perform blocking work.
  216. Notifications are delivered on the given queue. If the queue is blocked and
  217. notifications can't be delivered instantly, multiple notifications may be
  218. coalesced into a single notification.
  219. You must retain the returned token for as long as you want updates to continue
  220. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  221. @warning This method cannot be called when the containing Realm is read-only or frozen.
  222. @warning The queue must be a serial queue.
  223. @param block The block to be called whenever a change occurs.
  224. @param queue The serial queue to deliver notifications to.
  225. @return A token which must be held for as long as you want updates to be delivered.
  226. */
  227. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults<RLMObjectType> *_Nullable results,
  228. RLMCollectionChange *_Nullable change,
  229. NSError *_Nullable error))block
  230. queue:(nullable dispatch_queue_t)queue
  231. __attribute__((warn_unused_result));
  232. #pragma mark - Aggregating Property Values
  233. /**
  234. Returns the minimum (lowest) value of the given property among all the objects
  235. represented by the results collection.
  236. NSNumber *min = [results minOfProperty:@"age"];
  237. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  238. @param property The property whose minimum value is desired. Only properties of types `int`, `float`, `double`, and
  239. `NSDate` are supported.
  240. @return The minimum value of the property, or `nil` if the Results are empty.
  241. */
  242. - (nullable id)minOfProperty:(NSString *)property;
  243. /**
  244. Returns the maximum (highest) value of the given property among all the objects represented by the results collection.
  245. NSNumber *max = [results maxOfProperty:@"age"];
  246. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  247. @param property The property whose maximum value is desired. Only properties of
  248. types `int`, `float`, `double`, and `NSDate` are supported.
  249. @return The maximum value of the property, or `nil` if the Results are empty.
  250. */
  251. - (nullable id)maxOfProperty:(NSString *)property;
  252. /**
  253. Returns the sum of the values of a given property over all the objects represented by the results collection.
  254. NSNumber *sum = [results sumOfProperty:@"age"];
  255. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  256. @param property The property whose values should be summed. Only properties of
  257. types `int`, `float`, and `double` are supported.
  258. @return The sum of the given property.
  259. */
  260. - (NSNumber *)sumOfProperty:(NSString *)property;
  261. /**
  262. Returns the average value of a given property over the objects represented by the results collection.
  263. NSNumber *average = [results averageOfProperty:@"age"];
  264. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  265. @param property The property whose average value should be calculated. Only
  266. properties of types `int`, `float`, and `double` are supported.
  267. @return The average value of the given property, or `nil` if the Results are empty.
  268. */
  269. - (nullable NSNumber *)averageOfProperty:(NSString *)property;
  270. /// :nodoc:
  271. - (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index;
  272. #pragma mark - Freeze
  273. /**
  274. Indicates if the result are frozen.
  275. Frozen Results are immutable and can be accessed from any thread.The objects
  276. read from a frozen Results will also be frozen.
  277. */
  278. @property (nonatomic, readonly, getter=isFrozen) BOOL frozen;
  279. /**
  280. Returns a frozen (immutable) snapshot of these results.
  281. The frozen copy is an immutable collection which contains the same data as
  282. this collection currently contains, but will not update when writes are made
  283. to the containing Realm. Unlike live Results, frozen Results can be accessed
  284. from any thread.
  285. @warning This method cannot be called during a write transaction, or when the
  286. containing Realm is read-only.
  287. @warning Holding onto a frozen collection for an extended period while
  288. performing write transaction on the Realm may result in the Realm
  289. file growing to large sizes. See
  290. `RLMRealmConfiguration.maximumNumberOfActiveVersions` for more
  291. information.
  292. */
  293. - (instancetype)freeze;
  294. #pragma mark - Unavailable Methods
  295. /**
  296. `-[RLMResults init]` is not available because `RLMResults` cannot be created directly.
  297. `RLMResults` can be obtained by querying a Realm.
  298. */
  299. - (instancetype)init __attribute__((unavailable("RLMResults cannot be created directly")));
  300. /**
  301. `+[RLMResults new]` is not available because `RLMResults` cannot be created directly.
  302. `RLMResults` can be obtained by querying a Realm.
  303. */
  304. + (instancetype)new __attribute__((unavailable("RLMResults cannot be created directly")));
  305. @end
  306. /**
  307. `RLMLinkingObjects` is an auto-updating container type. It represents a collection of objects that link to its
  308. parent object.
  309. For more information, please see the "Inverse Relationships" section in the
  310. [documentation](https://realm.io/docs/objc/latest/#relationships).
  311. */
  312. @interface RLMLinkingObjects<RLMObjectType: RLMObject *> : RLMResults
  313. @end
  314. NS_ASSUME_NONNULL_END