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
26 `RLMResults` is an auto-updating container type in Realm returned from object
27 queries. It represents the results of the query in the form of a collection of objects.
29 `RLMResults` can be queried using the same predicates as `RLMObject` and `RLMArray`,
30 and you can chain queries to further filter results.
32 `RLMResults` always reflect the current state of the Realm on the current thread,
33 including during write transactions on the current thread. The one exception to
34 this is when using `for...in` fast enumeration, which will always enumerate
35 over the objects which matched the query when the enumeration is begun, even if
36 some of them are deleted or modified to be excluded by the filter during the
39 `RLMResults` are lazily evaluated the first time they are accessed; they only
40 run queries when the result of the query is requested. This means that
41 chaining several temporary `RLMResults` to sort and filter your data does not
42 perform any extra work processing the intermediate state.
44 Once the results have been evaluated or a notification block has been added,
45 the results are eagerly kept up-to-date, with the work done to keep them
46 up-to-date done on a background thread whenever possible.
48 `RLMResults` cannot be directly instantiated.
50 @interface RLMResults<RLMObjectType> : NSObject<RLMCollection, NSFastEnumeration>
52 #pragma mark - Properties
55 The number of objects in the results collection.
57 @property (nonatomic, readonly, assign) NSUInteger count;
60 The type of the objects in the results collection.
62 @property (nonatomic, readonly, assign) RLMPropertyType type;
65 Indicates whether the objects in the collection can be `nil`.
67 @property (nonatomic, readwrite, getter = isOptional) BOOL optional;
70 The class name of the objects contained in the results collection.
72 Will be `nil` if `type` is not RLMPropertyTypeObject.
74 @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
77 The Realm which manages this results collection.
79 @property (nonatomic, readonly) RLMRealm *realm;
82 Indicates if the results collection is no longer valid.
84 The results collection becomes invalid if `invalidate` is called on the containing `realm`.
85 An invalidated results collection can be accessed, but will always be empty.
87 @property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
89 #pragma mark - Accessing Objects from an RLMResults
92 Returns the object at the index specified.
94 @param index The index to look up.
96 @return An object of the type contained in the results collection.
98 - (RLMObjectType)objectAtIndex:(NSUInteger)index;
101 Returns the first object in the results collection.
103 Returns `nil` if called on an empty results collection.
105 @return An object of the type contained in the results collection.
107 - (nullable RLMObjectType)firstObject;
110 Returns the last object in the results collection.
112 Returns `nil` if called on an empty results collection.
114 @return An object of the type contained in the results collection.
116 - (nullable RLMObjectType)lastObject;
118 #pragma mark - Querying Results
121 Returns the index of an object in the results collection.
123 Returns `NSNotFound` if the object is not found in the results collection.
125 @param object An object (of the same type as returned from the `objectClassName` selector).
127 - (NSUInteger)indexOfObject:(RLMObjectType)object;
130 Returns the index of the first object in the results collection matching the predicate.
132 @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
134 @return The index of the object, or `NSNotFound` if the object is not found in the results collection.
136 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
139 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
142 Returns the index of the first object in the results collection matching the predicate.
144 @param predicate The predicate with which to filter the objects.
146 @return The index of the object, or `NSNotFound` if the object is not found in the results collection.
148 - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
151 Returns all the objects matching the given predicate in the results collection.
153 @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
155 @return An `RLMResults` of objects that match the given predicate.
157 - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat, ...;
160 - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
163 Returns all the objects matching the given predicate in the results collection.
165 @param predicate The predicate with which to filter the objects.
167 @return An `RLMResults` of objects that match the given predicate.
169 - (RLMResults<RLMObjectType> *)objectsWithPredicate:(NSPredicate *)predicate;
172 Returns a sorted `RLMResults` from an existing results collection.
174 @param keyPath The key path to sort by.
175 @param ascending The direction to sort in.
177 @return An `RLMResults` sorted by the specified key path.
179 - (RLMResults<RLMObjectType> *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
182 Returns a sorted `RLMResults` from an existing results collection.
184 @param properties An array of `RLMSortDescriptor`s to sort by.
186 @return An `RLMResults` sorted by the specified properties.
188 - (RLMResults<RLMObjectType> *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
191 Returns a distinct `RLMResults` from an existing results collection.
193 @param keyPaths The key paths used produce distinct results
195 @return An `RLMResults` made distinct based on the specified key paths
197 - (RLMResults<RLMObjectType> *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths;
199 #pragma mark - Notifications
202 Registers a block to be called each time the results collection changes.
204 The block will be asynchronously called with the initial results collection,
205 and then called again after each write transaction which changes either any
206 of the objects in the results, or which objects are in the results.
208 The `change` parameter will be `nil` the first time the block is called.
209 For each call after that, it will contain information about
210 which rows in the results collection were added, removed or modified. If a
211 write transaction did not modify any objects in the results collection,
212 the block is not called at all. See the `RLMCollectionChange` documentation for
213 information on how the changes are reported and an example of updating a
216 If an error occurs the block will be called with `nil` for the results
217 parameter and a non-`nil` error. Currently the only errors that can occur are
218 when opening the Realm on the background worker thread.
220 At the time when the block is called, the `RLMResults` object will be fully
221 evaluated and up-to-date, and as long as you do not perform a write transaction
222 on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will
223 never perform blocking work.
225 Notifications are delivered via the standard run loop, and so can't be
226 delivered while the run loop is blocked by other activity. When
227 notifications can't be delivered instantly, multiple notifications may be
228 coalesced into a single notification. This can include the notification
229 with the initial results. For example, the following code performs a write
230 transaction immediately after adding the notification block, so there is no
231 opportunity for the initial notification to be delivered first. As a
232 result, the initial notification will reflect the state of the Realm after
233 the write transaction.
235 RLMResults<Dog *> *results = [Dog allObjects];
236 NSLog(@"dogs.count: %zu", dogs.count); // => 0
237 self.token = [results addNotificationBlock:^(RLMResults *dogs,
238 RLMCollectionChange *changes,
240 // Only fired once for the example
241 NSLog(@"dogs.count: %zu", dogs.count); // => 1
243 [realm transactionWithBlock:^{
244 Dog *dog = [[Dog alloc] init];
246 [realm addObject:dog];
248 // end of run loop execution context
250 You must retain the returned token for as long as you want updates to continue
251 to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
253 @warning This method cannot be called during a write transaction, or when the
254 containing Realm is read-only.
256 @param block The block to be called whenever a change occurs.
257 @return A token which must be held for as long as you want updates to be delivered.
259 - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults<RLMObjectType> *__nullable results,
260 RLMCollectionChange *__nullable change,
261 NSError *__nullable error))block __attribute__((warn_unused_result));
263 #pragma mark - Aggregating Property Values
266 Returns the minimum (lowest) value of the given property among all the objects
267 represented by the results collection.
269 NSNumber *min = [results minOfProperty:@"age"];
271 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
273 @param property The property whose minimum value is desired. Only properties of types `int`, `float`, `double`, and
274 `NSDate` are supported.
276 @return The minimum value of the property, or `nil` if the Results are empty.
278 - (nullable id)minOfProperty:(NSString *)property;
281 Returns the maximum (highest) value of the given property among all the objects represented by the results collection.
283 NSNumber *max = [results maxOfProperty:@"age"];
285 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
287 @param property The property whose maximum value is desired. Only properties of
288 types `int`, `float`, `double`, and `NSDate` are supported.
290 @return The maximum value of the property, or `nil` if the Results are empty.
292 - (nullable id)maxOfProperty:(NSString *)property;
295 Returns the sum of the values of a given property over all the objects represented by the results collection.
297 NSNumber *sum = [results sumOfProperty:@"age"];
299 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
301 @param property The property whose values should be summed. Only properties of
302 types `int`, `float`, and `double` are supported.
304 @return The sum of the given property.
306 - (NSNumber *)sumOfProperty:(NSString *)property;
309 Returns the average value of a given property over the objects represented by the results collection.
311 NSNumber *average = [results averageOfProperty:@"age"];
313 @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
315 @param property The property whose average value should be calculated. Only
316 properties of types `int`, `float`, and `double` are supported.
318 @return The average value of the given property, or `nil` if the Results are empty.
320 - (nullable NSNumber *)averageOfProperty:(NSString *)property;
323 - (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index;
325 #pragma mark - Unavailable Methods
328 `-[RLMResults init]` is not available because `RLMResults` cannot be created directly.
329 `RLMResults` can be obtained by querying a Realm.
331 - (instancetype)init __attribute__((unavailable("RLMResults cannot be created directly")));
334 `+[RLMResults new]` is not available because `RLMResults` cannot be created directly.
335 `RLMResults` can be obtained by querying a Realm.
337 + (instancetype)new __attribute__((unavailable("RLMResults cannot be created directly")));
342 `RLMLinkingObjects` is an auto-updating container type. It represents a collection of objects that link to its
345 For more information, please see the "Inverse Relationships" section in the
346 [documentation](https://realm.io/docs/objc/latest/#relationships).
348 @interface RLMLinkingObjects<RLMObjectType: RLMObject *> : RLMResults
351 NS_ASSUME_NONNULL_END