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 <Foundation/Foundation.h>
21 #import <Realm/RLMThreadSafeReference.h>
23 NS_ASSUME_NONNULL_BEGIN
25 @class RLMRealm, RLMResults, RLMSortDescriptor, RLMNotificationToken, RLMCollectionChange;
26 typedef NS_ENUM(int32_t, RLMPropertyType);
29 A homogenous collection of Realm-managed objects. Examples of conforming types
30 include `RLMArray`, `RLMResults`, and `RLMLinkingObjects`.
32 @protocol RLMCollection <NSFastEnumeration, RLMThreadConfined>
36 #pragma mark - Properties
39 The number of objects in the collection.
41 @property (nonatomic, readonly, assign) NSUInteger count;
44 The type of the objects in the collection.
46 @property (nonatomic, readonly, assign) RLMPropertyType type;
49 Indicates whether the objects in the collection can be `nil`.
51 @property (nonatomic, readonly, getter = isOptional) BOOL optional;
54 The class name of the objects contained in the collection.
56 Will be `nil` if `type` is not RLMPropertyTypeObject.
58 @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
61 The Realm which manages the collection, or `nil` for unmanaged collections.
63 @property (nonatomic, readonly) RLMRealm *realm;
65 #pragma mark - Accessing Objects from a Collection
68 Returns the object at the index specified.
70 @param index The index to look up.
72 @return An object of the type contained in the collection.
74 - (id)objectAtIndex:(NSUInteger)index;
77 Returns the first object in the collection.
79 Returns `nil` if called on an empty collection.
81 @return An object of the type contained in the collection.
83 - (nullable id)firstObject;
86 Returns the last object in the collection.
88 Returns `nil` if called on an empty collection.
90 @return An object of the type contained in the collection.
92 - (nullable id)lastObject;
94 #pragma mark - Querying a Collection
97 Returns the index of an object in the collection.
99 Returns `NSNotFound` if the object is not found in the collection.
101 @param object An object (of the same type as returned from the `objectClassName` selector).
103 - (NSUInteger)indexOfObject:(id)object;
106 Returns the index of the first object in the collection matching the predicate.
108 @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
110 @return The index of the object, or `NSNotFound` if the object is not found in the collection.
112 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
115 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
118 Returns the index of the first object in the collection matching the predicate.
120 @param predicate The predicate with which to filter the objects.
122 @return The index of the object, or `NSNotFound` if the object is not found in the collection.
124 - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
127 Returns all objects matching the given predicate in the collection.
129 @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
131 @return An `RLMResults` containing objects that match the given predicate.
133 - (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...;
136 - (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
139 Returns all objects matching the given predicate in the collection.
141 @param predicate The predicate with which to filter the objects.
143 @return An `RLMResults` containing objects that match the given predicate.
145 - (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate;
148 Returns a sorted `RLMResults` from the collection.
150 @param keyPath The keyPath to sort by.
151 @param ascending The direction to sort in.
153 @return An `RLMResults` sorted by the specified key path.
155 - (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
158 Returns a sorted `RLMResults` from the collection.
160 @param properties An array of `RLMSortDescriptor`s to sort by.
162 @return An `RLMResults` sorted by the specified properties.
164 - (RLMResults *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
167 - (id)objectAtIndexedSubscript:(NSUInteger)index;
170 Returns an `NSArray` containing the results of invoking `valueForKey:` using `key` on each of the collection's objects.
172 @param key The name of the property.
174 @return An `NSArray` containing results.
176 - (nullable id)valueForKey:(NSString *)key;
179 Invokes `setValue:forKey:` on each of the collection's objects using the specified `value` and `key`.
181 @warning This method may only be called during a write transaction.
183 @param value The object value.
184 @param key The name of the property.
186 - (void)setValue:(nullable id)value forKey:(NSString *)key;
188 #pragma mark - Notifications
191 Registers a block to be called each time the collection changes.
193 The block will be asynchronously called with the initial collection, and then
194 called again after each write transaction which changes either any of the
195 objects in the collection, or which objects are in the collection.
197 The `change` parameter will be `nil` the first time the block is called.
198 For each call after that, it will contain information about
199 which rows in the collection were added, removed or modified. If a write transaction
200 did not modify any objects in this collection, the block is not called at all.
201 See the `RLMCollectionChange` documentation for information on how the changes
202 are reported and an example of updating a `UITableView`.
204 If an error occurs the block will be called with `nil` for the collection
205 parameter and a non-`nil` error. Currently the only errors that can occur are
206 when opening the Realm on the background worker thread.
208 At the time when the block is called, the collection object will be fully
209 evaluated and up-to-date, and as long as you do not perform a write transaction
210 on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will
211 never perform blocking work.
213 Notifications are delivered via the standard run loop, and so can't be
214 delivered while the run loop is blocked by other activity. When
215 notifications can't be delivered instantly, multiple notifications may be
216 coalesced into a single notification. This can include the notification
217 with the initial collection. For example, the following code performs a write
218 transaction immediately after adding the notification block, so there is no
219 opportunity for the initial notification to be delivered first. As a
220 result, the initial notification will reflect the state of the Realm after
221 the write transaction.
223 id<RLMCollection> collection = [Dog allObjects];
224 NSLog(@"dogs.count: %zu", dogs.count); // => 0
225 self.token = [collection addNotificationBlock:^(id<RLMCollection> dogs,
226 RLMCollectionChange *changes,
228 // Only fired once for the example
229 NSLog(@"dogs.count: %zu", dogs.count); // => 1
231 [realm transactionWithBlock:^{
232 Dog *dog = [[Dog alloc] init];
234 [realm addObject:dog];
236 // end of run loop execution context
238 You must retain the returned token for as long as you want updates to continue
239 to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
241 @warning This method cannot be called during a write transaction, or when the
242 containing Realm is read-only.
244 @param block The block to be called each time the collection changes.
245 @return A token which must be held for as long as you want collection notifications to be delivered.
247 - (RLMNotificationToken *)addNotificationBlock:(void (^)(id<RLMCollection> __nullable collection,
248 RLMCollectionChange *__nullable change,
249 NSError *__nullable error))block __attribute__((warn_unused_result));
251 #pragma mark - Aggregating Property Values
254 Returns the minimum (lowest) value of the given property among all the objects
257 NSNumber *min = [results minOfProperty:@"age"];
259 @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.
264 @return The minimum value of the property, or `nil` if the Results are empty.
266 - (nullable id)minOfProperty:(NSString *)property;
269 Returns the maximum (highest) value of the given property among all the objects
272 NSNumber *max = [results maxOfProperty:@"age"];
274 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
276 @param property The property whose maximum value is desired. Only properties of
277 types `int`, `float`, `double`, and `NSDate` are supported.
279 @return The maximum value of the property, or `nil` if the Results are empty.
281 - (nullable id)maxOfProperty:(NSString *)property;
284 Returns the sum of the values of a given property over all the objects in the collection.
286 NSNumber *sum = [results sumOfProperty:@"age"];
288 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
290 @param property The property whose values should be summed. Only properties of
291 types `int`, `float`, and `double` are supported.
293 @return The sum of the given property.
295 - (NSNumber *)sumOfProperty:(NSString *)property;
298 Returns the average value of a given property over the objects in the collection.
300 NSNumber *average = [results averageOfProperty:@"age"];
302 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
304 @param property The property whose average value should be calculated. Only
305 properties of types `int`, `float`, and `double` are supported.
307 @return The average value of the given property, or `nil` if the Results are empty.
309 - (nullable NSNumber *)averageOfProperty:(NSString *)property;
314 An `RLMSortDescriptor` stores a property name and a sort order for use with
315 `sortedResultsUsingDescriptors:`. It is similar to `NSSortDescriptor`, but supports
316 only the subset of functionality which can be efficiently run by Realm's query
319 `RLMSortDescriptor` instances are immutable.
321 @interface RLMSortDescriptor : NSObject
323 #pragma mark - Properties
326 The key path which the sort descriptor orders results by.
328 @property (nonatomic, readonly) NSString *keyPath;
331 Whether the descriptor sorts in ascending or descending order.
333 @property (nonatomic, readonly) BOOL ascending;
335 #pragma mark - Methods
338 Returns a new sort descriptor for the given key path and sort direction.
340 + (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
343 Returns a copy of the receiver with the sort direction reversed.
345 - (instancetype)reversedSortDescriptor;
350 A `RLMCollectionChange` object encapsulates information about changes to collections
351 that are reported by Realm notifications.
353 `RLMCollectionChange` is passed to the notification blocks registered with
354 `-addNotificationBlock` on `RLMArray` and `RLMResults`, and reports what rows in the
355 collection changed since the last time the notification block was called.
357 The change information is available in two formats: a simple array of row
358 indices in the collection for each type of change, and an array of index paths
359 in a requested section suitable for passing directly to `UITableView`'s batch
360 update methods. A complete example of updating a `UITableView` named `tv`:
363 [tv deleteRowsAtIndexPaths:[changes deletionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
364 [tv insertRowsAtIndexPaths:[changes insertionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
365 [tv reloadRowsAtIndexPaths:[changes modificationsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
368 All of the arrays in an `RLMCollectionChange` are always sorted in ascending order.
370 @interface RLMCollectionChange : NSObject
371 /// The indices of objects in the previous version of the collection which have
372 /// been removed from this one.
373 @property (nonatomic, readonly) NSArray<NSNumber *> *deletions;
375 /// The indices in the new version of the collection which were newly inserted.
376 @property (nonatomic, readonly) NSArray<NSNumber *> *insertions;
379 The indices in the new version of the collection which were modified.
381 For `RLMResults`, this means that one or more of the properties of the object at
382 that index were modified (or an object linked to by that object was
385 For `RLMArray`, the array itself being modified to contain a
386 different object at that index will also be reported as a modification.
388 @property (nonatomic, readonly) NSArray<NSNumber *> *modifications;
390 /// Returns the index paths of the deletion indices in the given section.
391 - (NSArray<NSIndexPath *> *)deletionsInSection:(NSUInteger)section;
393 /// Returns the index paths of the insertion indices in the given section.
394 - (NSArray<NSIndexPath *> *)insertionsInSection:(NSUInteger)section;
396 /// Returns the index paths of the modification indices in the given section.
397 - (NSArray<NSIndexPath *> *)modificationsInSection:(NSUInteger)section;
400 NS_ASSUME_NONNULL_END