RLMCollection.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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/Foundation.h>
  19. #import <Realm/RLMConstants.h>
  20. #import <Realm/RLMThreadSafeReference.h>
  21. NS_ASSUME_NONNULL_BEGIN
  22. @class RLMRealm, RLMResults, RLMSortDescriptor, RLMNotificationToken, RLMCollectionChange;
  23. typedef RLM_CLOSED_ENUM(int32_t, RLMPropertyType);
  24. /**
  25. A homogenous collection of Realm-managed objects. Examples of conforming types
  26. include `RLMArray`, `RLMResults`, and `RLMLinkingObjects`.
  27. */
  28. @protocol RLMCollection <NSFastEnumeration, RLMThreadConfined>
  29. @required
  30. #pragma mark - Properties
  31. /**
  32. The number of objects in the collection.
  33. */
  34. @property (nonatomic, readonly, assign) NSUInteger count;
  35. /**
  36. The type of the objects in the collection.
  37. */
  38. @property (nonatomic, readonly, assign) RLMPropertyType type;
  39. /**
  40. Indicates whether the objects in the collection can be `nil`.
  41. */
  42. @property (nonatomic, readonly, getter = isOptional) BOOL optional;
  43. /**
  44. The class name of the objects contained in the collection.
  45. Will be `nil` if `type` is not RLMPropertyTypeObject.
  46. */
  47. @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
  48. /**
  49. The Realm which manages the collection, or `nil` for unmanaged collections.
  50. */
  51. @property (nonatomic, readonly) RLMRealm *realm;
  52. #pragma mark - Accessing Objects from a Collection
  53. /**
  54. Returns the object at the index specified.
  55. @param index The index to look up.
  56. @return An object of the type contained in the collection.
  57. */
  58. - (id)objectAtIndex:(NSUInteger)index;
  59. /**
  60. Returns the first object in the collection.
  61. Returns `nil` if called on an empty collection.
  62. @return An object of the type contained in the collection.
  63. */
  64. - (nullable id)firstObject;
  65. /**
  66. Returns the last object in the collection.
  67. Returns `nil` if called on an empty collection.
  68. @return An object of the type contained in the collection.
  69. */
  70. - (nullable id)lastObject;
  71. #pragma mark - Querying a Collection
  72. /**
  73. Returns the index of an object in the collection.
  74. Returns `NSNotFound` if the object is not found in the collection.
  75. @param object An object (of the same type as returned from the `objectClassName` selector).
  76. */
  77. - (NSUInteger)indexOfObject:(id)object;
  78. /**
  79. Returns the index of the first object in the collection matching the predicate.
  80. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  81. @return The index of the object, or `NSNotFound` if the object is not found in the collection.
  82. */
  83. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
  84. /// :nodoc:
  85. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
  86. /**
  87. Returns the index of the first object in the collection matching the predicate.
  88. @param predicate The predicate with which to filter the objects.
  89. @return The index of the object, or `NSNotFound` if the object is not found in the collection.
  90. */
  91. - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
  92. /**
  93. Returns all objects matching the given predicate in the collection.
  94. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  95. @return An `RLMResults` containing objects that match the given predicate.
  96. */
  97. - (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...;
  98. /// :nodoc:
  99. - (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
  100. /**
  101. Returns all objects matching the given predicate in the collection.
  102. @param predicate The predicate with which to filter the objects.
  103. @return An `RLMResults` containing objects that match the given predicate.
  104. */
  105. - (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate;
  106. /**
  107. Returns a sorted `RLMResults` from the collection.
  108. @param keyPath The keyPath to sort by.
  109. @param ascending The direction to sort in.
  110. @return An `RLMResults` sorted by the specified key path.
  111. */
  112. - (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
  113. /**
  114. Returns a sorted `RLMResults` from the collection.
  115. @param properties An array of `RLMSortDescriptor`s to sort by.
  116. @return An `RLMResults` sorted by the specified properties.
  117. */
  118. - (RLMResults *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
  119. /// :nodoc:
  120. - (id)objectAtIndexedSubscript:(NSUInteger)index;
  121. /**
  122. Returns an `NSArray` containing the results of invoking `valueForKey:` using `key` on each of the collection's objects.
  123. @param key The name of the property.
  124. @return An `NSArray` containing results.
  125. */
  126. - (nullable id)valueForKey:(NSString *)key;
  127. /**
  128. Invokes `setValue:forKey:` on each of the collection's objects using the specified `value` and `key`.
  129. @warning This method may only be called during a write transaction.
  130. @param value The object value.
  131. @param key The name of the property.
  132. */
  133. - (void)setValue:(nullable id)value forKey:(NSString *)key;
  134. #pragma mark - Notifications
  135. /**
  136. Registers a block to be called each time the collection changes.
  137. The block will be asynchronously called with the initial collection, and then
  138. called again after each write transaction which changes either any of the
  139. objects in the collection, or which objects are in the collection.
  140. The `change` parameter will be `nil` the first time the block is called.
  141. For each call after that, it will contain information about
  142. which rows in the collection were added, removed or modified. If a write transaction
  143. did not modify any objects in this collection, the block is not called at all.
  144. See the `RLMCollectionChange` documentation for information on how the changes
  145. are reported and an example of updating a `UITableView`.
  146. If an error occurs the block will be called with `nil` for the collection
  147. parameter and a non-`nil` error. Currently the only errors that can occur are
  148. when opening the Realm on the background worker thread.
  149. At the time when the block is called, the collection object will be fully
  150. evaluated and up-to-date, and as long as you do not perform a write transaction
  151. on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will
  152. never perform blocking work.
  153. Notifications are delivered via the standard run loop, and so can't be
  154. delivered while the run loop is blocked by other activity. When
  155. notifications can't be delivered instantly, multiple notifications may be
  156. coalesced into a single notification. This can include the notification
  157. with the initial collection. For example, the following code performs a write
  158. transaction immediately after adding the notification block, so there is no
  159. opportunity for the initial notification to be delivered first. As a
  160. result, the initial notification will reflect the state of the Realm after
  161. the write transaction.
  162. id<RLMCollection> collection = [Dog allObjects];
  163. NSLog(@"dogs.count: %zu", dogs.count); // => 0
  164. self.token = [collection addNotificationBlock:^(id<RLMCollection> dogs,
  165. RLMCollectionChange *changes,
  166. NSError *error) {
  167. // Only fired once for the example
  168. NSLog(@"dogs.count: %zu", dogs.count); // => 1
  169. }];
  170. [realm transactionWithBlock:^{
  171. Dog *dog = [[Dog alloc] init];
  172. dog.name = @"Rex";
  173. [realm addObject:dog];
  174. }];
  175. // end of run loop execution context
  176. You must retain the returned token for as long as you want updates to continue
  177. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  178. @warning This method cannot be called during a write transaction, or when the
  179. containing Realm is read-only.
  180. @param block The block to be called each time the collection changes.
  181. @return A token which must be held for as long as you want collection notifications to be delivered.
  182. */
  183. - (RLMNotificationToken *)addNotificationBlock:(void (^)(id<RLMCollection> __nullable collection,
  184. RLMCollectionChange *__nullable change,
  185. NSError *__nullable error))block __attribute__((warn_unused_result));
  186. #pragma mark - Aggregating Property Values
  187. /**
  188. Returns the minimum (lowest) value of the given property among all the objects
  189. in the collection.
  190. NSNumber *min = [results minOfProperty:@"age"];
  191. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  192. @param property The property whose minimum value is desired. Only properties of
  193. types `int`, `float`, `double`, and `NSDate` are supported.
  194. @return The minimum value of the property, or `nil` if the Results are empty.
  195. */
  196. - (nullable id)minOfProperty:(NSString *)property;
  197. /**
  198. Returns the maximum (highest) value of the given property among all the objects
  199. in the collection.
  200. NSNumber *max = [results maxOfProperty:@"age"];
  201. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  202. @param property The property whose maximum value is desired. Only properties of
  203. types `int`, `float`, `double`, and `NSDate` are supported.
  204. @return The maximum value of the property, or `nil` if the Results are empty.
  205. */
  206. - (nullable id)maxOfProperty:(NSString *)property;
  207. /**
  208. Returns the sum of the values of a given property over all the objects in the collection.
  209. NSNumber *sum = [results sumOfProperty:@"age"];
  210. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  211. @param property The property whose values should be summed. Only properties of
  212. types `int`, `float`, and `double` are supported.
  213. @return The sum of the given property.
  214. */
  215. - (NSNumber *)sumOfProperty:(NSString *)property;
  216. /**
  217. Returns the average value of a given property over the objects in the collection.
  218. NSNumber *average = [results averageOfProperty:@"age"];
  219. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  220. @param property The property whose average value should be calculated. Only
  221. properties of types `int`, `float`, and `double` are supported.
  222. @return The average value of the given property, or `nil` if the Results are empty.
  223. */
  224. - (nullable NSNumber *)averageOfProperty:(NSString *)property;
  225. @end
  226. /**
  227. An `RLMSortDescriptor` stores a property name and a sort order for use with
  228. `sortedResultsUsingDescriptors:`. It is similar to `NSSortDescriptor`, but supports
  229. only the subset of functionality which can be efficiently run by Realm's query
  230. engine.
  231. `RLMSortDescriptor` instances are immutable.
  232. */
  233. @interface RLMSortDescriptor : NSObject
  234. #pragma mark - Properties
  235. /**
  236. The key path which the sort descriptor orders results by.
  237. */
  238. @property (nonatomic, readonly) NSString *keyPath;
  239. /**
  240. Whether the descriptor sorts in ascending or descending order.
  241. */
  242. @property (nonatomic, readonly) BOOL ascending;
  243. #pragma mark - Methods
  244. /**
  245. Returns a new sort descriptor for the given key path and sort direction.
  246. */
  247. + (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
  248. /**
  249. Returns a copy of the receiver with the sort direction reversed.
  250. */
  251. - (instancetype)reversedSortDescriptor;
  252. @end
  253. /**
  254. A `RLMCollectionChange` object encapsulates information about changes to collections
  255. that are reported by Realm notifications.
  256. `RLMCollectionChange` is passed to the notification blocks registered with
  257. `-addNotificationBlock` on `RLMArray` and `RLMResults`, and reports what rows in the
  258. collection changed since the last time the notification block was called.
  259. The change information is available in two formats: a simple array of row
  260. indices in the collection for each type of change, and an array of index paths
  261. in a requested section suitable for passing directly to `UITableView`'s batch
  262. update methods. A complete example of updating a `UITableView` named `tv`:
  263. [tv beginUpdates];
  264. [tv deleteRowsAtIndexPaths:[changes deletionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  265. [tv insertRowsAtIndexPaths:[changes insertionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  266. [tv reloadRowsAtIndexPaths:[changes modificationsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  267. [tv endUpdates];
  268. All of the arrays in an `RLMCollectionChange` are always sorted in ascending order.
  269. */
  270. @interface RLMCollectionChange : NSObject
  271. /// The indices of objects in the previous version of the collection which have
  272. /// been removed from this one.
  273. @property (nonatomic, readonly) NSArray<NSNumber *> *deletions;
  274. /// The indices in the new version of the collection which were newly inserted.
  275. @property (nonatomic, readonly) NSArray<NSNumber *> *insertions;
  276. /**
  277. The indices in the new version of the collection which were modified.
  278. For `RLMResults`, this means that one or more of the properties of the object at
  279. that index were modified (or an object linked to by that object was
  280. modified).
  281. For `RLMArray`, the array itself being modified to contain a
  282. different object at that index will also be reported as a modification.
  283. */
  284. @property (nonatomic, readonly) NSArray<NSNumber *> *modifications;
  285. /// Returns the index paths of the deletion indices in the given section.
  286. - (NSArray<NSIndexPath *> *)deletionsInSection:(NSUInteger)section;
  287. /// Returns the index paths of the insertion indices in the given section.
  288. - (NSArray<NSIndexPath *> *)insertionsInSection:(NSUInteger)section;
  289. /// Returns the index paths of the modification indices in the given section.
  290. - (NSArray<NSIndexPath *> *)modificationsInSection:(NSUInteger)section;
  291. @end
  292. NS_ASSUME_NONNULL_END