1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2014 Realm Inc.
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 ////////////////////////////////////////////////////////////////////////////
19 #import <Realm/RLMCollection.h>
21 NS_ASSUME_NONNULL_BEGIN
23 @class RLMObject, RLMResults<RLMObjectType>;
26 `RLMArray` is the container type in Realm used to define to-many relationships.
28 Unlike an `NSArray`, `RLMArray`s hold a single type, specified by the `objectClassName` property.
29 This is referred to in these docs as the “type” of the array.
31 When declaring an `RLMArray` property, the type must be marked as conforming to a
32 protocol by the same name as the objects it should contain (see the
33 `RLM_ARRAY_TYPE` macro). In addition, the property can be declared using Objective-C
34 generics for better compile-time type safety.
36 RLM_ARRAY_TYPE(ObjectType)
38 @property RLMArray<ObjectType *><ObjectType> *arrayOfObjectTypes;
40 `RLMArray`s can be queried with the same predicates as `RLMObject` and `RLMResult`s.
42 `RLMArray`s cannot be created directly. `RLMArray` properties on `RLMObject`s are
43 lazily created when accessed, or can be obtained by querying a Realm.
45 ### Key-Value Observing
47 `RLMArray` supports array key-value observing on `RLMArray` properties on `RLMObject`
48 subclasses, and the `invalidated` property on `RLMArray` instances themselves is
49 key-value observing compliant when the `RLMArray` is attached to a managed
50 `RLMObject` (`RLMArray`s on unmanaged `RLMObject`s will never become invalidated).
52 Because `RLMArray`s are attached to the object which they are a property of, they
53 do not require using the mutable collection proxy objects from
54 `-mutableArrayValueForKey:` or KVC-compatible mutation methods on the containing
55 object. Instead, you can call the mutation methods on the `RLMArray` directly.
58 @interface RLMArray<RLMObjectType> : NSObject<RLMCollection, NSFastEnumeration>
60 #pragma mark - Properties
63 The number of objects in the array.
65 @property (nonatomic, readonly, assign) NSUInteger count;
68 The type of the objects in the array.
70 @property (nonatomic, readonly, assign) RLMPropertyType type;
73 Indicates whether the objects in the collection can be `nil`.
75 @property (nonatomic, readonly, getter = isOptional) BOOL optional;
78 The class name of the objects contained in the array.
80 Will be `nil` if `type` is not RLMPropertyTypeObject.
82 @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
85 The Realm which manages the array. Returns `nil` for unmanaged arrays.
87 @property (nonatomic, readonly, nullable) RLMRealm *realm;
90 Indicates if the array can no longer be accessed.
92 @property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
94 #pragma mark - Accessing Objects from an Array
97 Returns the object at the index specified.
99 @param index The index to look up.
101 @return An object of the type contained in the array.
103 - (RLMObjectType)objectAtIndex:(NSUInteger)index;
106 Returns the first object in the array.
108 Returns `nil` if called on an empty array.
110 @return An object of the type contained in the array.
112 - (nullable RLMObjectType)firstObject;
115 Returns the last object in the array.
117 Returns `nil` if called on an empty array.
119 @return An object of the type contained in the array.
121 - (nullable RLMObjectType)lastObject;
125 #pragma mark - Adding, Removing, and Replacing Objects in an Array
128 Adds an object to the end of the array.
130 @warning This method may only be called during a write transaction.
132 @param object An object of the type contained in the array.
134 - (void)addObject:(RLMObjectType)object;
137 Adds an array of objects to the end of the array.
139 @warning This method may only be called during a write transaction.
141 @param objects An enumerable object such as `NSArray` or `RLMResults` which contains objects of the
142 same class as the array.
144 - (void)addObjects:(id<NSFastEnumeration>)objects;
147 Inserts an object at the given index.
149 Throws an exception if the index exceeds the bounds of the array.
151 @warning This method may only be called during a write transaction.
153 @param anObject An object of the type contained in the array.
154 @param index The index at which to insert the object.
156 - (void)insertObject:(RLMObjectType)anObject atIndex:(NSUInteger)index;
159 Removes an object at the given index.
161 Throws an exception if the index exceeds the bounds of the array.
163 @warning This method may only be called during a write transaction.
165 @param index The array index identifying the object to be removed.
167 - (void)removeObjectAtIndex:(NSUInteger)index;
170 Removes the last object in the array.
172 This is a no-op if the array is already empty.
174 @warning This method may only be called during a write transaction.
176 - (void)removeLastObject;
179 Removes all objects from the array.
181 @warning This method may only be called during a write transaction.
183 - (void)removeAllObjects;
186 Replaces an object at the given index with a new object.
188 Throws an exception if the index exceeds the bounds of the array.
190 @warning This method may only be called during a write transaction.
192 @param index The index of the object to be replaced.
193 @param anObject An object (of the same type as returned from the `objectClassName` selector).
195 - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(RLMObjectType)anObject;
198 Moves the object at the given source index to the given destination index.
200 Throws an exception if the index exceeds the bounds of the array.
202 @warning This method may only be called during a write transaction.
204 @param sourceIndex The index of the object to be moved.
205 @param destinationIndex The index to which the object at `sourceIndex` should be moved.
207 - (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex;
210 Exchanges the objects in the array at given indices.
212 Throws an exception if either index exceeds the bounds of the array.
214 @warning This method may only be called during a write transaction.
216 @param index1 The index of the object which should replace the object at index `index2`.
217 @param index2 The index of the object which should replace the object at index `index1`.
219 - (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2;
221 #pragma mark - Querying an Array
224 Returns the index of an object in the array.
226 Returns `NSNotFound` if the object is not found in the array.
228 @param object An object (of the same type as returned from the `objectClassName` selector).
230 - (NSUInteger)indexOfObject:(RLMObjectType)object;
233 Returns the index of the first object in the array matching the predicate.
235 @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
237 @return The index of the object, or `NSNotFound` if the object is not found in the array.
239 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
242 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
245 Returns the index of the first object in the array matching the predicate.
247 @param predicate The predicate with which to filter the objects.
249 @return The index of the object, or `NSNotFound` if the object is not found in the array.
251 - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
254 Returns all the objects matching the given predicate in the array.
256 @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
258 @return An `RLMResults` of objects that match the given predicate.
260 - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat, ...;
263 - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
266 Returns all the objects matching the given predicate in the array.
268 @param predicate The predicate with which to filter the objects.
270 @return An `RLMResults` of objects that match the given predicate
272 - (RLMResults<RLMObjectType> *)objectsWithPredicate:(NSPredicate *)predicate;
275 Returns a sorted `RLMResults` from the array.
277 @param keyPath The key path to sort by.
278 @param ascending The direction to sort in.
280 @return An `RLMResults` sorted by the specified key path.
282 - (RLMResults<RLMObjectType> *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
285 Returns a sorted `RLMResults` from the array.
287 @param properties An array of `RLMSortDescriptor`s to sort by.
289 @return An `RLMResults` sorted by the specified properties.
291 - (RLMResults<RLMObjectType> *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
294 - (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index;
297 - (void)setObject:(RLMObjectType)newValue atIndexedSubscript:(NSUInteger)index;
299 #pragma mark - Notifications
302 Registers a block to be called each time the array changes.
304 The block will be asynchronously called with the initial array, and then
305 called again after each write transaction which changes any of the objects in
306 the array, which objects are in the results, or the order of the objects in the
309 The `changes` parameter will be `nil` the first time the block is called.
310 For each call after that, it will contain information about
311 which rows in the array were added, removed or modified. If a write transaction
312 did not modify any objects in the array, the block is not called at all.
313 See the `RLMCollectionChange` documentation for information on how the changes
314 are reported and an example of updating a `UITableView`.
316 If an error occurs the block will be called with `nil` for the results
317 parameter and a non-`nil` error. Currently the only errors that can occur are
318 when opening the Realm on the background worker thread.
320 Notifications are delivered via the standard run loop, and so can't be
321 delivered while the run loop is blocked by other activity. When
322 notifications can't be delivered instantly, multiple notifications may be
323 coalesced into a single notification. This can include the notification
324 with the initial results. For example, the following code performs a write
325 transaction immediately after adding the notification block, so there is no
326 opportunity for the initial notification to be delivered first. As a
327 result, the initial notification will reflect the state of the Realm after
328 the write transaction.
330 Person *person = [[Person allObjectsInRealm:realm] firstObject];
331 NSLog(@"person.dogs.count: %zu", person.dogs.count); // => 0
332 self.token = [person.dogs addNotificationBlock(RLMArray<Dog *> *dogs,
333 RLMCollectionChange *changes,
335 // Only fired once for the example
336 NSLog(@"dogs.count: %zu", dogs.count) // => 1
338 [realm transactionWithBlock:^{
339 Dog *dog = [[Dog alloc] init];
341 [person.dogs addObject:dog];
343 // end of run loop execution context
345 You must retain the returned token for as long as you want updates to continue
346 to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
348 @warning This method cannot be called during a write transaction, or when the
349 containing Realm is read-only.
350 @warning This method may only be called on a managed array.
352 @param block The block to be called each time the array changes.
353 @return A token which must be held for as long as you want updates to be delivered.
355 - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray<RLMObjectType> *__nullable array,
356 RLMCollectionChange *__nullable changes,
357 NSError *__nullable error))block __attribute__((warn_unused_result));
359 #pragma mark - Aggregating Property Values
362 Returns the minimum (lowest) value of the given property among all the objects in the array.
364 NSNumber *min = [object.arrayProperty minOfProperty:@"age"];
366 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
368 @param property The property whose minimum value is desired. Only properties of
369 types `int`, `float`, `double`, and `NSDate` are supported.
371 @return The minimum value of the property, or `nil` if the array is empty.
373 - (nullable id)minOfProperty:(NSString *)property;
376 Returns the maximum (highest) value of the given property among all the objects in the array.
378 NSNumber *max = [object.arrayProperty maxOfProperty:@"age"];
380 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
382 @param property The property whose maximum value is desired. Only properties of
383 types `int`, `float`, `double`, and `NSDate` are supported.
385 @return The maximum value of the property, or `nil` if the array is empty.
387 - (nullable id)maxOfProperty:(NSString *)property;
390 Returns the sum of the values of a given property over all the objects in the array.
392 NSNumber *sum = [object.arrayProperty sumOfProperty:@"age"];
394 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
396 @param property The property whose values should be summed. Only properties of
397 types `int`, `float`, and `double` are supported.
399 @return The sum of the given property.
401 - (NSNumber *)sumOfProperty:(NSString *)property;
404 Returns the average value of a given property over the objects in the array.
406 NSNumber *average = [object.arrayProperty averageOfProperty:@"age"];
408 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
410 @param property The property whose average value should be calculated. Only
411 properties of types `int`, `float`, and `double` are supported.
413 @return The average value of the given property, or `nil` if the array is empty.
415 - (nullable NSNumber *)averageOfProperty:(NSString *)property;
418 #pragma mark - Unavailable Methods
421 `-[RLMArray init]` is not available because `RLMArray`s cannot be created directly.
422 `RLMArray` properties on `RLMObject`s are lazily created when accessed.
424 - (instancetype)init __attribute__((unavailable("RLMArrays cannot be created directly")));
427 `+[RLMArray new]` is not available because `RLMArray`s cannot be created directly.
428 `RLMArray` properties on `RLMObject`s are lazily created when accessed.
430 + (instancetype)new __attribute__((unavailable("RLMArrays cannot be created directly")));
435 @interface RLMArray (Swift)
436 // for use only in Swift class definitions
437 - (instancetype)initWithObjectClassName:(NSString *)objectClassName;
440 NS_ASSUME_NONNULL_END