RLMArray.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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, RLMResults<RLMObjectType>;
  21. /**
  22. `RLMArray` is the container type in Realm used to define to-many relationships.
  23. Unlike an `NSArray`, `RLMArray`s hold a single type, specified by the `objectClassName` property.
  24. This is referred to in these docs as the “type” of the array.
  25. When declaring an `RLMArray` property, the type must be marked as conforming to a
  26. protocol by the same name as the objects it should contain (see the
  27. `RLM_ARRAY_TYPE` macro). In addition, the property can be declared using Objective-C
  28. generics for better compile-time type safety.
  29. RLM_ARRAY_TYPE(ObjectType)
  30. ...
  31. @property RLMArray<ObjectType *><ObjectType> *arrayOfObjectTypes;
  32. `RLMArray`s can be queried with the same predicates as `RLMObject` and `RLMResult`s.
  33. `RLMArray`s cannot be created directly. `RLMArray` properties on `RLMObject`s are
  34. lazily created when accessed, or can be obtained by querying a Realm.
  35. ### Key-Value Observing
  36. `RLMArray` supports array key-value observing on `RLMArray` properties on `RLMObject`
  37. subclasses, and the `invalidated` property on `RLMArray` instances themselves is
  38. key-value observing compliant when the `RLMArray` is attached to a managed
  39. `RLMObject` (`RLMArray`s on unmanaged `RLMObject`s will never become invalidated).
  40. Because `RLMArray`s are attached to the object which they are a property of, they
  41. do not require using the mutable collection proxy objects from
  42. `-mutableArrayValueForKey:` or KVC-compatible mutation methods on the containing
  43. object. Instead, you can call the mutation methods on the `RLMArray` directly.
  44. */
  45. @interface RLMArray<RLMObjectType> : NSObject<RLMCollection, NSFastEnumeration>
  46. #pragma mark - Properties
  47. /**
  48. The number of objects in the array.
  49. */
  50. @property (nonatomic, readonly, assign) NSUInteger count;
  51. /**
  52. The type of the objects in the array.
  53. */
  54. @property (nonatomic, readonly, assign) RLMPropertyType type;
  55. /**
  56. Indicates whether the objects in the collection can be `nil`.
  57. */
  58. @property (nonatomic, readonly, getter = isOptional) BOOL optional;
  59. /**
  60. The class name of the objects contained in the array.
  61. Will be `nil` if `type` is not RLMPropertyTypeObject.
  62. */
  63. @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
  64. /**
  65. The Realm which manages the array. Returns `nil` for unmanaged arrays.
  66. */
  67. @property (nonatomic, readonly, nullable) RLMRealm *realm;
  68. /**
  69. Indicates if the array can no longer be accessed.
  70. */
  71. @property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
  72. /**
  73. Indicates if the array is frozen.
  74. Frozen arrays are immutable and can be accessed from any thread. Frozen arrays
  75. are created by calling `-freeze` on a managed live array. Unmanaged arrays are
  76. never frozen.
  77. */
  78. @property (nonatomic, readonly, getter = isFrozen) BOOL frozen;
  79. #pragma mark - Accessing Objects from an Array
  80. /**
  81. Returns the object at the index specified.
  82. @param index The index to look up.
  83. @return An object of the type contained in the array.
  84. */
  85. - (RLMObjectType)objectAtIndex:(NSUInteger)index;
  86. /**
  87. Returns the first object in the array.
  88. Returns `nil` if called on an empty array.
  89. @return An object of the type contained in the array.
  90. */
  91. - (nullable RLMObjectType)firstObject;
  92. /**
  93. Returns the last object in the array.
  94. Returns `nil` if called on an empty array.
  95. @return An object of the type contained in the array.
  96. */
  97. - (nullable RLMObjectType)lastObject;
  98. #pragma mark - Adding, Removing, and Replacing Objects in an Array
  99. /**
  100. Adds an object to the end of the array.
  101. @warning This method may only be called during a write transaction.
  102. @param object An object of the type contained in the array.
  103. */
  104. - (void)addObject:(RLMObjectType)object;
  105. /**
  106. Adds an array of objects to the end of the array.
  107. @warning This method may only be called during a write transaction.
  108. @param objects An enumerable object such as `NSArray` or `RLMResults` which contains objects of the
  109. same class as the array.
  110. */
  111. - (void)addObjects:(id<NSFastEnumeration>)objects;
  112. /**
  113. Inserts an object at the given index.
  114. Throws an exception if the index exceeds the bounds of the array.
  115. @warning This method may only be called during a write transaction.
  116. @param anObject An object of the type contained in the array.
  117. @param index The index at which to insert the object.
  118. */
  119. - (void)insertObject:(RLMObjectType)anObject atIndex:(NSUInteger)index;
  120. /**
  121. Removes an object at the given index.
  122. Throws an exception if the index exceeds the bounds of the array.
  123. @warning This method may only be called during a write transaction.
  124. @param index The array index identifying the object to be removed.
  125. */
  126. - (void)removeObjectAtIndex:(NSUInteger)index;
  127. /**
  128. Removes the last object in the array.
  129. This is a no-op if the array is already empty.
  130. @warning This method may only be called during a write transaction.
  131. */
  132. - (void)removeLastObject;
  133. /**
  134. Removes all objects from the array.
  135. @warning This method may only be called during a write transaction.
  136. */
  137. - (void)removeAllObjects;
  138. /**
  139. Replaces an object at the given index with a new object.
  140. Throws an exception if the index exceeds the bounds of the array.
  141. @warning This method may only be called during a write transaction.
  142. @param index The index of the object to be replaced.
  143. @param anObject An object (of the same type as returned from the `objectClassName` selector).
  144. */
  145. - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(RLMObjectType)anObject;
  146. /**
  147. Moves the object at the given source index to the given destination index.
  148. Throws an exception if the index exceeds the bounds of the array.
  149. @warning This method may only be called during a write transaction.
  150. @param sourceIndex The index of the object to be moved.
  151. @param destinationIndex The index to which the object at `sourceIndex` should be moved.
  152. */
  153. - (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex;
  154. /**
  155. Exchanges the objects in the array at given indices.
  156. Throws an exception if either index exceeds the bounds of the array.
  157. @warning This method may only be called during a write transaction.
  158. @param index1 The index of the object which should replace the object at index `index2`.
  159. @param index2 The index of the object which should replace the object at index `index1`.
  160. */
  161. - (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2;
  162. #pragma mark - Querying an Array
  163. /**
  164. Returns the index of an object in the array.
  165. Returns `NSNotFound` if the object is not found in the array.
  166. @param object An object (of the same type as returned from the `objectClassName` selector).
  167. */
  168. - (NSUInteger)indexOfObject:(RLMObjectType)object;
  169. /**
  170. Returns the index of the first object in the array matching the predicate.
  171. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  172. @return The index of the object, or `NSNotFound` if the object is not found in the array.
  173. */
  174. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
  175. /// :nodoc:
  176. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
  177. /**
  178. Returns the index of the first object in the array matching the predicate.
  179. @param predicate The predicate with which to filter the objects.
  180. @return The index of the object, or `NSNotFound` if the object is not found in the array.
  181. */
  182. - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
  183. /**
  184. Returns all the objects matching the given predicate in the array.
  185. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  186. @return An `RLMResults` of objects that match the given predicate.
  187. */
  188. - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat, ...;
  189. /// :nodoc:
  190. - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
  191. /**
  192. Returns all the objects matching the given predicate in the array.
  193. @param predicate The predicate with which to filter the objects.
  194. @return An `RLMResults` of objects that match the given predicate
  195. */
  196. - (RLMResults<RLMObjectType> *)objectsWithPredicate:(NSPredicate *)predicate;
  197. /**
  198. Returns a sorted `RLMResults` from the array.
  199. @param keyPath The key path to sort by.
  200. @param ascending The direction to sort in.
  201. @return An `RLMResults` sorted by the specified key path.
  202. */
  203. - (RLMResults<RLMObjectType> *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
  204. /**
  205. Returns a sorted `RLMResults` from the array.
  206. @param properties An array of `RLMSortDescriptor`s to sort by.
  207. @return An `RLMResults` sorted by the specified properties.
  208. */
  209. - (RLMResults<RLMObjectType> *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
  210. /**
  211. Returns a distinct `RLMResults` from the array.
  212. @param keyPaths The key paths to distinct on.
  213. @return An `RLMResults` with the distinct values of the keypath(s).
  214. */
  215. - (RLMResults<RLMObjectType> *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths;
  216. /// :nodoc:
  217. - (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index;
  218. /// :nodoc:
  219. - (void)setObject:(RLMObjectType)newValue atIndexedSubscript:(NSUInteger)index;
  220. #pragma mark - Notifications
  221. /**
  222. Registers a block to be called each time the array changes.
  223. The block will be asynchronously called with the initial array, and then
  224. called again after each write transaction which changes any of the objects in
  225. the array, which objects are in the results, or the order of the objects in the
  226. array.
  227. The `changes` parameter will be `nil` the first time the block is called.
  228. For each call after that, it will contain information about
  229. which rows in the array were added, removed or modified. If a write transaction
  230. did not modify any objects in the array, the block is not called at all.
  231. See the `RLMCollectionChange` documentation for information on how the changes
  232. are reported and an example of updating a `UITableView`.
  233. If an error occurs the block will be called with `nil` for the results
  234. parameter and a non-`nil` error. Currently the only errors that can occur are
  235. when opening the Realm on the background worker thread.
  236. Notifications are delivered via the standard run loop, and so can't be
  237. delivered while the run loop is blocked by other activity. When
  238. notifications can't be delivered instantly, multiple notifications may be
  239. coalesced into a single notification. This can include the notification
  240. with the initial results. For example, the following code performs a write
  241. transaction immediately after adding the notification block, so there is no
  242. opportunity for the initial notification to be delivered first. As a
  243. result, the initial notification will reflect the state of the Realm after
  244. the write transaction.
  245. Person *person = [[Person allObjectsInRealm:realm] firstObject];
  246. NSLog(@"person.dogs.count: %zu", person.dogs.count); // => 0
  247. self.token = [person.dogs addNotificationBlock(RLMArray<Dog *> *dogs,
  248. RLMCollectionChange *changes,
  249. NSError *error) {
  250. // Only fired once for the example
  251. NSLog(@"dogs.count: %zu", dogs.count) // => 1
  252. }];
  253. [realm transactionWithBlock:^{
  254. Dog *dog = [[Dog alloc] init];
  255. dog.name = @"Rex";
  256. [person.dogs addObject:dog];
  257. }];
  258. // end of run loop execution context
  259. You must retain the returned token for as long as you want updates to continue
  260. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  261. @warning This method cannot be called during a write transaction, or when the
  262. containing Realm is read-only.
  263. @warning This method may only be called on a non-frozen managed array.
  264. @param block The block to be called each time the array changes.
  265. @return A token which must be held for as long as you want updates to be delivered.
  266. */
  267. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray<RLMObjectType> *_Nullable array,
  268. RLMCollectionChange *_Nullable changes,
  269. NSError *_Nullable error))block
  270. __attribute__((warn_unused_result));
  271. /**
  272. Registers a block to be called each time the array changes.
  273. The block will be asynchronously called with the initial array, and then
  274. called again after each write transaction which changes any of the objects in
  275. the array, which objects are in the results, or the order of the objects in the
  276. array.
  277. The `changes` parameter will be `nil` the first time the block is called.
  278. For each call after that, it will contain information about
  279. which rows in the array were added, removed or modified. If a write transaction
  280. did not modify any objects in the array, the block is not called at all.
  281. See the `RLMCollectionChange` documentation for information on how the changes
  282. are reported and an example of updating a `UITableView`.
  283. If an error occurs the block will be called with `nil` for the results
  284. parameter and a non-`nil` error. Currently the only errors that can occur are
  285. when opening the Realm on the background worker thread.
  286. Notifications are delivered on the given queue. If the queue is blocked and
  287. notifications can't be delivered instantly, multiple notifications may be
  288. coalesced into a single notification.
  289. You must retain the returned token for as long as you want updates to continue
  290. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  291. @warning This method cannot be called when the containing Realm is read-only or frozen.
  292. @warning The queue must be a serial queue.
  293. @param block The block to be called whenever a change occurs.
  294. @param queue The serial queue to deliver notifications to.
  295. @return A token which must be held for as long as you want updates to be delivered.
  296. */
  297. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray<RLMObjectType> *_Nullable array,
  298. RLMCollectionChange *_Nullable changes,
  299. NSError *_Nullable error))block
  300. queue:(nullable dispatch_queue_t)queue
  301. __attribute__((warn_unused_result));
  302. #pragma mark - Aggregating Property Values
  303. /**
  304. Returns the minimum (lowest) value of the given property among all the objects in the array.
  305. NSNumber *min = [object.arrayProperty minOfProperty:@"age"];
  306. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  307. @param property The property whose minimum value is desired. Only properties of
  308. types `int`, `float`, `double`, and `NSDate` are supported.
  309. @return The minimum value of the property, or `nil` if the array is empty.
  310. */
  311. - (nullable id)minOfProperty:(NSString *)property;
  312. /**
  313. Returns the maximum (highest) value of the given property among all the objects in the array.
  314. NSNumber *max = [object.arrayProperty maxOfProperty:@"age"];
  315. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  316. @param property The property whose maximum value is desired. Only properties of
  317. types `int`, `float`, `double`, and `NSDate` are supported.
  318. @return The maximum value of the property, or `nil` if the array is empty.
  319. */
  320. - (nullable id)maxOfProperty:(NSString *)property;
  321. /**
  322. Returns the sum of the values of a given property over all the objects in the array.
  323. NSNumber *sum = [object.arrayProperty sumOfProperty:@"age"];
  324. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  325. @param property The property whose values should be summed. Only properties of
  326. types `int`, `float`, and `double` are supported.
  327. @return The sum of the given property.
  328. */
  329. - (NSNumber *)sumOfProperty:(NSString *)property;
  330. /**
  331. Returns the average value of a given property over the objects in the array.
  332. NSNumber *average = [object.arrayProperty averageOfProperty:@"age"];
  333. @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
  334. @param property The property whose average value should be calculated. Only
  335. properties of types `int`, `float`, and `double` are supported.
  336. @return The average value of the given property, or `nil` if the array is empty.
  337. */
  338. - (nullable NSNumber *)averageOfProperty:(NSString *)property;
  339. #pragma mark - Freeze
  340. /**
  341. Returns a frozen (immutable) snapshot of this array.
  342. The frozen copy is an immutable array which contains the same data as this
  343. array currently contains, but will not update when writes are made to the
  344. containing Realm. Unlike live arrays, frozen arrays can be accessed from any
  345. thread.
  346. @warning This method cannot be called during a write transaction, or when the
  347. containing Realm is read-only.
  348. @warning This method may only be called on a managed array.
  349. @warning Holding onto a frozen array for an extended period while performing
  350. write transaction on the Realm may result in the Realm file growing
  351. to large sizes. See `RLMRealmConfiguration.maximumNumberOfActiveVersions`
  352. for more information.
  353. */
  354. - (instancetype)freeze;
  355. #pragma mark - Unavailable Methods
  356. /**
  357. `-[RLMArray init]` is not available because `RLMArray`s cannot be created directly.
  358. `RLMArray` properties on `RLMObject`s are lazily created when accessed.
  359. */
  360. - (instancetype)init __attribute__((unavailable("RLMArrays cannot be created directly")));
  361. /**
  362. `+[RLMArray new]` is not available because `RLMArray`s cannot be created directly.
  363. `RLMArray` properties on `RLMObject`s are lazily created when accessed.
  364. */
  365. + (instancetype)new __attribute__((unavailable("RLMArrays cannot be created directly")));
  366. @end
  367. /// :nodoc:
  368. @interface RLMArray (Swift)
  369. // for use only in Swift class definitions
  370. - (instancetype)initWithObjectClassName:(NSString *)objectClassName;
  371. @end
  372. NS_ASSUME_NONNULL_END