added iOS source code
[wl-app.git] / iOS / Pods / Realm / include / RLMArray.h
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
19 #import <Realm/RLMCollection.h>
20
21 NS_ASSUME_NONNULL_BEGIN
22
23 @class RLMObject, RLMResults<RLMObjectType>;
24
25 /**
26  `RLMArray` is the container type in Realm used to define to-many relationships.
27
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.
30
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.
35
36      RLM_ARRAY_TYPE(ObjectType)
37      ...
38      @property RLMArray<ObjectType *><ObjectType> *arrayOfObjectTypes;
39
40  `RLMArray`s can be queried with the same predicates as `RLMObject` and `RLMResult`s.
41
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.
44
45  ### Key-Value Observing
46
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).
51
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.
56  */
57
58 @interface RLMArray<RLMObjectType> : NSObject<RLMCollection, NSFastEnumeration>
59
60 #pragma mark - Properties
61
62 /**
63  The number of objects in the array.
64  */
65 @property (nonatomic, readonly, assign) NSUInteger count;
66
67 /**
68  The type of the objects in the array.
69  */
70 @property (nonatomic, readonly, assign) RLMPropertyType type;
71
72 /**
73  Indicates whether the objects in the collection can be `nil`.
74  */
75 @property (nonatomic, readonly, getter = isOptional) BOOL optional;
76
77 /**
78  The class name  of the objects contained in the array.
79
80  Will be `nil` if `type` is not RLMPropertyTypeObject.
81  */
82 @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
83
84 /**
85  The Realm which manages the array. Returns `nil` for unmanaged arrays.
86  */
87 @property (nonatomic, readonly, nullable) RLMRealm *realm;
88
89 /**
90  Indicates if the array can no longer be accessed.
91  */
92 @property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
93
94 #pragma mark - Accessing Objects from an Array
95
96 /**
97  Returns the object at the index specified.
98
99  @param index   The index to look up.
100
101  @return An object of the type contained in the array.
102  */
103 - (RLMObjectType)objectAtIndex:(NSUInteger)index;
104
105 /**
106  Returns the first object in the array.
107
108  Returns `nil` if called on an empty array.
109
110  @return An object of the type contained in the array.
111  */
112 - (nullable RLMObjectType)firstObject;
113
114 /**
115  Returns the last object in the array.
116
117  Returns `nil` if called on an empty array.
118
119  @return An object of the type contained in the array.
120  */
121 - (nullable RLMObjectType)lastObject;
122
123
124
125 #pragma mark - Adding, Removing, and Replacing Objects in an Array
126
127 /**
128  Adds an object to the end of the array.
129
130  @warning This method may only be called during a write transaction.
131
132  @param object  An object of the type contained in the array.
133  */
134 - (void)addObject:(RLMObjectType)object;
135
136 /**
137  Adds an array of objects to the end of the array.
138
139  @warning This method may only be called during a write transaction.
140
141  @param objects     An enumerable object such as `NSArray` or `RLMResults` which contains objects of the
142                     same class as the array.
143  */
144 - (void)addObjects:(id<NSFastEnumeration>)objects;
145
146 /**
147  Inserts an object at the given index.
148
149  Throws an exception if the index exceeds the bounds of the array.
150
151  @warning This method may only be called during a write transaction.
152
153  @param anObject  An object of the type contained in the array.
154  @param index   The index at which to insert the object.
155  */
156 - (void)insertObject:(RLMObjectType)anObject atIndex:(NSUInteger)index;
157
158 /**
159  Removes an object at the given index.
160
161  Throws an exception if the index exceeds the bounds of the array.
162
163  @warning This method may only be called during a write transaction.
164
165  @param index   The array index identifying the object to be removed.
166  */
167 - (void)removeObjectAtIndex:(NSUInteger)index;
168
169 /**
170  Removes the last object in the array.
171
172  This is a no-op if the array is already empty.
173
174  @warning This method may only be called during a write transaction.
175 */
176 - (void)removeLastObject;
177
178 /**
179  Removes all objects from the array.
180
181  @warning This method may only be called during a write transaction.
182  */
183 - (void)removeAllObjects;
184
185 /**
186  Replaces an object at the given index with a new object.
187
188  Throws an exception if the index exceeds the bounds of the array.
189
190  @warning This method may only be called during a write transaction.
191
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).
194  */
195 - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(RLMObjectType)anObject;
196
197 /**
198  Moves the object at the given source index to the given destination index.
199
200  Throws an exception if the index exceeds the bounds of the array.
201
202  @warning This method may only be called during a write transaction.
203
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.
206  */
207 - (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex;
208
209 /**
210  Exchanges the objects in the array at given indices.
211
212  Throws an exception if either index exceeds the bounds of the array.
213
214  @warning This method may only be called during a write transaction.
215
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`.
218  */
219 - (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2;
220
221 #pragma mark - Querying an Array
222
223 /**
224  Returns the index of an object in the array.
225
226  Returns `NSNotFound` if the object is not found in the array.
227
228  @param object  An object (of the same type as returned from the `objectClassName` selector).
229  */
230 - (NSUInteger)indexOfObject:(RLMObjectType)object;
231
232 /**
233  Returns the index of the first object in the array matching the predicate.
234
235  @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
236
237  @return    The index of the object, or `NSNotFound` if the object is not found in the array.
238  */
239 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...;
240
241 /// :nodoc:
242 - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args;
243
244 /**
245  Returns the index of the first object in the array matching the predicate.
246
247  @param predicate   The predicate with which to filter the objects.
248
249  @return    The index of the object, or `NSNotFound` if the object is not found in the array.
250  */
251 - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate;
252
253 /**
254  Returns all the objects matching the given predicate in the array.
255
256  @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
257
258  @return                An `RLMResults` of objects that match the given predicate.
259  */
260 - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat, ...;
261
262 /// :nodoc:
263 - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
264
265 /**
266  Returns all the objects matching the given predicate in the array.
267
268  @param predicate   The predicate with which to filter the objects.
269
270  @return            An `RLMResults` of objects that match the given predicate
271  */
272 - (RLMResults<RLMObjectType> *)objectsWithPredicate:(NSPredicate *)predicate;
273
274 /**
275  Returns a sorted `RLMResults` from the array.
276
277  @param keyPath     The key path to sort by.
278  @param ascending   The direction to sort in.
279
280  @return    An `RLMResults` sorted by the specified key path.
281  */
282 - (RLMResults<RLMObjectType> *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
283
284 /**
285  Returns a sorted `RLMResults` from the array.
286
287  @param properties  An array of `RLMSortDescriptor`s to sort by.
288
289  @return    An `RLMResults` sorted by the specified properties.
290  */
291 - (RLMResults<RLMObjectType> *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
292
293 /// :nodoc:
294 - (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index;
295
296 /// :nodoc:
297 - (void)setObject:(RLMObjectType)newValue atIndexedSubscript:(NSUInteger)index;
298
299 #pragma mark - Notifications
300
301 /**
302  Registers a block to be called each time the array changes.
303
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
307  array.
308
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`.
315
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.
319
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.
329
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,
334                                                     NSError *error) {
335          // Only fired once for the example
336          NSLog(@"dogs.count: %zu", dogs.count) // => 1
337      }];
338      [realm transactionWithBlock:^{
339          Dog *dog = [[Dog alloc] init];
340          dog.name = @"Rex";
341          [person.dogs addObject:dog];
342      }];
343      // end of run loop execution context
344
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.
347
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.
351
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.
354  */
355 - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray<RLMObjectType> *__nullable array,
356                                                          RLMCollectionChange *__nullable changes,
357                                                          NSError *__nullable error))block __attribute__((warn_unused_result));
358
359 #pragma mark - Aggregating Property Values
360
361 /**
362  Returns the minimum (lowest) value of the given property among all the objects in the array.
363
364      NSNumber *min = [object.arrayProperty minOfProperty:@"age"];
365
366  @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
367
368  @param property The property whose minimum value is desired. Only properties of
369                  types `int`, `float`, `double`, and `NSDate` are supported.
370
371  @return The minimum value of the property, or `nil` if the array is empty.
372  */
373 - (nullable id)minOfProperty:(NSString *)property;
374
375 /**
376  Returns the maximum (highest) value of the given property among all the objects in the array.
377
378      NSNumber *max = [object.arrayProperty maxOfProperty:@"age"];
379
380  @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
381
382  @param property The property whose maximum value is desired. Only properties of
383                  types `int`, `float`, `double`, and `NSDate` are supported.
384
385  @return The maximum value of the property, or `nil` if the array is empty.
386  */
387 - (nullable id)maxOfProperty:(NSString *)property;
388
389 /**
390  Returns the sum of the values of a given property over all the objects in the array.
391
392      NSNumber *sum = [object.arrayProperty sumOfProperty:@"age"];
393
394  @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
395
396  @param property The property whose values should be summed. Only properties of
397                  types `int`, `float`, and `double` are supported.
398
399  @return The sum of the given property.
400  */
401 - (NSNumber *)sumOfProperty:(NSString *)property;
402
403 /**
404  Returns the average value of a given property over the objects in the array.
405
406      NSNumber *average = [object.arrayProperty averageOfProperty:@"age"];
407
408  @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties.
409
410  @param property The property whose average value should be calculated. Only
411                  properties of types `int`, `float`, and `double` are supported.
412
413  @return    The average value of the given property, or `nil` if the array is empty.
414  */
415 - (nullable NSNumber *)averageOfProperty:(NSString *)property;
416
417
418 #pragma mark - Unavailable Methods
419
420 /**
421  `-[RLMArray init]` is not available because `RLMArray`s cannot be created directly.
422  `RLMArray` properties on `RLMObject`s are lazily created when accessed.
423  */
424 - (instancetype)init __attribute__((unavailable("RLMArrays cannot be created directly")));
425
426 /**
427  `+[RLMArray new]` is not available because `RLMArray`s cannot be created directly.
428  `RLMArray` properties on `RLMObject`s are lazily created when accessed.
429  */
430 + (instancetype)new __attribute__((unavailable("RLMArrays cannot be created directly")));
431
432 @end
433
434 /// :nodoc:
435 @interface RLMArray (Swift)
436 // for use only in Swift class definitions
437 - (instancetype)initWithObjectClassName:(NSString *)objectClassName;
438 @end
439
440 NS_ASSUME_NONNULL_END