RLMArray.h 15 KB

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