RLMCollection.h 15 KB

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