RLMCollection

Objective-C

@protocol RLMCollection <NSFastEnumeration, RLMThreadConfined>

Swift

protocol RLMCollection : NSFastEnumeration, RLMThreadConfined

A homogenous collection of Realm-managed objects. Examples of conforming types include RLMArray, RLMSet, RLMResults, and RLMLinkingObjects.

Properties

  • The number of objects in the collection.

    Declaration

    Objective-C

    @property (nonatomic, readonly) NSUInteger count;

    Swift

    var count: UInt { get }
  • The type of the objects in the collection.

    Declaration

    Objective-C

    @property (nonatomic, readonly) RLMPropertyType type;

    Swift

    var type: RLMPropertyType { get }
  • Indicates whether the objects in the collection can be nil.

    Declaration

    Objective-C

    @property (nonatomic, readonly, getter=isOptional) BOOL optional;

    Swift

    var isOptional: Bool { get }
  • The class name of the objects contained in the collection.

    Will be nil if type is not RLMPropertyTypeObject.

    Declaration

    Objective-C

    @property (nonatomic, copy, readonly, nullable) NSString *objectClassName;

    Swift

    var objectClassName: String? { get }
  • The Realm which manages this collection, if any.

    Declaration

    Objective-C

    @property (nonatomic, readonly, nullable) RLMRealm *realm;

    Swift

    var realm: RLMRealm? { get }
  • Indicates if the collection is no longer valid.

    The collection becomes invalid if invalidate is called on the managing Realm. Unmanaged collections are never invalidated.

    Declaration

    Objective-C

    @property (nonatomic, readonly, getter=isInvalidated) BOOL invalidated;

    Swift

    var isInvalidated: Bool { get }

Accessing Objects from a Collection

  • Returns the object at the index specified.

    Declaration

    Objective-C

    - (nonnull id)objectAtIndex:(NSUInteger)index;

    Swift

    func object(at index: UInt) -> Any

    Parameters

    index

    The index to look up.

    Return Value

    An object of the type contained in the collection.

  • Returns an array containing the objects in the collection at the indexes specified by a given index set. nil will be returned if the index set contains an index out of the collections bounds.

    Declaration

    Objective-C

    - (nullable NSArray *)objectsAtIndexes:(nonnull NSIndexSet *)indexes;

    Swift

    optional func objects(at indexes: IndexSet) -> [Any]?

    Parameters

    indexes

    The indexes in the collection to retrieve objects from.

    Return Value

    The objects at the specified indexes.

  • Returns the first object in the collection.

    RLMSet is not ordered, and so for sets this will return an arbitrary object in the set. It is not guaraneed to be a different object from what lastObject gives even if the set has multiple objects in it.

    Returns nil if called on an empty collection.

    Declaration

    Objective-C

    - (nullable id)firstObject;

    Swift

    optional func firstObject() -> Any?

    Return Value

    An object of the type contained in the collection.

  • Returns the last object in the collection.

    RLMSet is not ordered, and so for sets this will return an arbitrary object in the set. It is not guaraneed to be a different object from what firstObject gives even if the set has multiple objects in it.

    Returns nil if called on an empty collection.

    Declaration

    Objective-C

    - (nullable id)lastObject;

    Swift

    optional func lastObject() -> Any?

    Return Value

    An object of the type contained in the collection.

  • Returns the index of an object in the collection.

    Returns NSNotFound if the object is not found in the collection.

    Declaration

    Objective-C

    - (NSUInteger)indexOfObject:(nonnull id)object;

    Swift

    optional func index(of object: Any) -> UInt

    Parameters

    object

    An object (of the same type as returned from the objectClassName selector).

  • Returns the index of the first object in the collection matching the predicate.

    Declaration

    Objective-C

    - (NSUInteger)indexOfObjectWhere:(nonnull NSString *)predicateFormat, ...;

    Parameters

    predicateFormat

    A predicate format string, optionally followed by a variable number of arguments.

    Return Value

    The index of the object, or NSNotFound if the object is not found in the collection.

  • Returns the index of the first object in the collection matching the predicate.

    Declaration

    Objective-C

    - (NSUInteger)indexOfObjectWithPredicate:(nonnull NSPredicate *)predicate;

    Swift

    optional func indexOfObject(with predicate: NSPredicate) -> UInt

    Parameters

    predicate

    The predicate with which to filter the objects.

    Return Value

    The index of the object, or NSNotFound if the object is not found in the collection.

Querying a Collection

  • Returns all objects matching the given predicate in the collection.

    This is only supported for managed collections.

    Declaration

    Objective-C

    - (nonnull RLMResults *)objectsWhere:(nonnull NSString *)predicateFormat, ...;

    Parameters

    predicateFormat

    A predicate format string, optionally followed by a variable number of arguments.

    Return Value

    An RLMResults containing objects that match the given predicate.

  • Returns all objects matching the given predicate in the collection.

    This is only supported for managed collections.

    Declaration

    Objective-C

    - (nonnull RLMResults *)objectsWithPredicate:(nonnull NSPredicate *)predicate;

    Swift

    func objects(with predicate: NSPredicate) -> RLMResults

    Parameters

    predicate

    The predicate with which to filter the objects.

    Return Value

    An RLMResults containing objects that match the given predicate.

  • Returns a sorted RLMResults from the collection.

    This is only supported for managed collections.

    Declaration

    Objective-C

    - (nonnull RLMResults *)sortedResultsUsingKeyPath:(nonnull NSString *)keyPath
                                            ascending:(BOOL)ascending;

    Swift

    func sortedResults(usingKeyPath keyPath: String, ascending: Bool) -> RLMResults

    Parameters

    keyPath

    The keyPath to sort by.

    ascending

    The direction to sort in.

    Return Value

    An RLMResults sorted by the specified key path.

  • Returns a sorted RLMResults from the collection.

    This is only supported for managed collections.

    Declaration

    Objective-C

    - (nonnull RLMResults *)sortedResultsUsingDescriptors:
        (nonnull NSArray<RLMSortDescriptor *> *)properties;

    Swift

    func sortedResults(using properties: [RLMSortDescriptor]) -> RLMResults

    Parameters

    properties

    An array of RLMSortDescriptors to sort by.

    Return Value

    An RLMResults sorted by the specified properties.

  • Returns a distinct RLMResults from the collection.

    This is only supported for managed collections.

    Declaration

    Objective-C

    - (nonnull RLMResults *)distinctResultsUsingKeyPaths:
        (nonnull NSArray<NSString *> *)keyPaths;

    Swift

    func distinctResults(usingKeyPaths keyPaths: [String]) -> RLMResults

    Parameters

    keyPaths

    The key paths used produce distinct results

    Return Value

    An RLMResults made distinct based on the specified key paths

  • Returns an NSArray containing the results of invoking valueForKey: using key on each of the collection’s objects.

    Declaration

    Objective-C

    - (nullable id)valueForKey:(nonnull NSString *)key;

    Swift

    func value(forKey key: String) -> Any?

    Parameters

    key

    The name of the property.

    Return Value

    An NSArray containing results.

  • Returns the value for the derived property identified by a given key path.

    Declaration

    Objective-C

    - (nullable id)valueForKeyPath:(nonnull NSString *)keyPath;

    Swift

    func value(forKeyPath keyPath: String) -> Any?

    Parameters

    keyPath

    A key path of the form relationship.property (with one or more relationships).

    Return Value

    The value for the derived property identified by keyPath.

  • Invokes setValue:forKey: on each of the collection’s objects using the specified value and key.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)setValue:(nullable id)value forKey:(nonnull NSString *)key;

    Swift

    func setValue(_ value: Any?, forKey key: String)

    Parameters

    value

    The object value.

    key

    The name of the property.

Notifications

  • Registers a block to be called each time the collection changes.

    The block will be asynchronously called with the initial collection, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection.

    The change parameter will be nil the first time the block is called. For each call after that, it will contain information about which rows in the collection were added, removed or modified. If a write transaction did not modify any objects in the results collection, the block is not called at all. See the RLMCollectionChange documentation for information on how the changes are reported and an example of updating a UITableView.

    The error parameter is present only for backwards compatiblity and will always be nil.

    At the time when the block is called, the collection object will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call -[RLMRealm refresh], accessing it will never perform blocking work.

    Notifications are delivered via the standard run loop, and so can’t be delivered while the run loop is blocked by other activity. When notifications can’t be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial results. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction.

    RLMResults *results = [Dog allObjects]; NSLog(@“dogs.count: %zu”, dogs.count); // => 0 self.token = [results addNotificationBlock:^(RLMResults *dogs, RLMCollectionChange *changes, NSError *error) { // Only fired once for the example NSLog(@“dogs.count: %zu”, dogs.count); // => 1 }]; [realm transactionWithBlock:^{ Dog *dog = [[Dog alloc] init]; dog.name = @“Rex”; [realm addObject:dog]; }]; // end of run loop execution context

    You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call -invalidate on the token.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only or frozen.

    Declaration

    Objective-C

    - (nonnull RLMNotificationToken *)addNotificationBlock:
        (nonnull void (^)(RLMResults *_Nullable, RLMCollectionChange *_Nullable,
                          NSError *_Nullable))block;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMResults?, RLMCollectionChange?, Error?) -> Void) -> RLMNotificationToken

    Parameters

    block

    The block to be called whenever a change occurs.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

  • Registers a block to be called each time the collection changes.

    The block will be asynchronously called with the initial collection, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection.

    The change parameter will be nil the first time the block is called. For each call after that, it will contain information about which rows in the collection were added, removed or modified. If a write transaction did not modify any objects in the results collection, the block is not called at all. See the RLMCollectionChange documentation for information on how the changes are reported and an example of updating a UITableView.

    The error parameter is present only for backwards compatiblity and will always be nil.

    At the time when the block is called, the collection object will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call -[RLMRealm refresh], accessing it will never perform blocking work.

    Notifications are delivered on the given queue. If the queue is blocked and notifications can’t be delivered instantly, multiple notifications may be coalesced into a single notification.

    You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call -invalidate on the token.

    Warning

    This method cannot be called when the containing Realm is read-only or frozen.

    Warning

    The queue must be a serial queue.

    Declaration

    Objective-C

    - (nonnull RLMNotificationToken *)
        addNotificationBlock:(nonnull void (^)(RLMResults *_Nullable,
                                               RLMCollectionChange *_Nullable,
                                               NSError *_Nullable))block
                       queue:(nullable dispatch_queue_t)queue;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMResults?, RLMCollectionChange?, Error?) -> Void, queue: DispatchQueue?) -> RLMNotificationToken

    Parameters

    block

    The block to be called whenever a change occurs.

    queue

    The serial queue to deliver notifications to.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

  • Registers a block to be called each time the collection changes.

    The block will be asynchronously called with the initial collection, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection.

    The change parameter will be nil the first time the block is called. For each call after that, it will contain information about which rows in the collection were added, removed or modified. If a write transaction did not modify any objects in the results collection, the block is not called at all. See the RLMCollectionChange documentation for information on how the changes are reported and an example of updating a UITableView.

    The error parameter is present only for backwards compatiblity and will always be nil.

    At the time when the block is called, the collection object will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call -[RLMRealm refresh], accessing it will never perform blocking work.

    Notifications are delivered on the given queue. If the queue is blocked and notifications can’t be delivered instantly, multiple notifications may be coalesced into a single notification.

    You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call -invalidate on the token.

    Warning

    This method cannot be called when the containing Realm is read-only or frozen.

    Warning

    The queue must be a serial queue.

    Declaration

    Objective-C

    - (nonnull RLMNotificationToken *)
        addNotificationBlock:(nonnull void (^)(RLMResults *_Nullable,
                                               RLMCollectionChange *_Nullable,
                                               NSError *_Nullable))block
                    keyPaths:(nullable NSArray<NSString *> *)keyPaths
                       queue:(nullable dispatch_queue_t)queue;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMResults?, RLMCollectionChange?, Error?) -> Void, keyPaths: [String]?, queue: DispatchQueue?) -> RLMNotificationToken

    Parameters

    block

    The block to be called whenever a change occurs.

    queue

    The serial queue to deliver notifications to.

    keyPaths

    The block will be called for changes occurring on these keypaths. If no key paths are given, notifications are delivered for every property key path.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

Sectioned Results

Aggregating Property Values

  • Returns the minimum (lowest) value of the given property among all the objects in the collection.

    NSNumber *min = [results minOfProperty:@"age"];
    

    Warning

    You cannot use this method on RLMObject, RLMArray, and NSData properties.

    Declaration

    Objective-C

    - (nullable id)minOfProperty:(nonnull NSString *)property;

    Swift

    func min(ofProperty property: String) -> Any?

    Parameters

    property

    The property whose minimum value is desired. Only properties of types int, float, double, and NSDate are supported.

    Return Value

    The minimum value of the property, or nil if the Results are empty.

  • Returns the maximum (highest) value of the given property among all the objects in the collection.

    NSNumber *max = [results maxOfProperty:@"age"];
    

    Warning

    You cannot use this method on RLMObject, RLMArray, and NSData properties.

    Declaration

    Objective-C

    - (nullable id)maxOfProperty:(nonnull NSString *)property;

    Swift

    func max(ofProperty property: String) -> Any?

    Parameters

    property

    The property whose maximum value is desired. Only properties of types int, float, double, and NSDate are supported.

    Return Value

    The maximum value of the property, or nil if the Results are empty.

  • Returns the sum of the values of a given property over all the objects in the collection.

    NSNumber *sum = [results sumOfProperty:@"age"];
    

    Warning

    You cannot use this method on RLMObject, RLMArray, and NSData properties.

    Declaration

    Objective-C

    - (nonnull NSNumber *)sumOfProperty:(nonnull NSString *)property;

    Swift

    func sum(ofProperty property: String) -> NSNumber

    Parameters

    property

    The property whose values should be summed. Only properties of types int, float, and double are supported.

    Return Value

    The sum of the given property.

  • Returns the average value of a given property over the objects in the collection.

    NSNumber *average = [results averageOfProperty:@"age"];
    

    Warning

    You cannot use this method on RLMObject, RLMArray, and NSData properties.

    Declaration

    Objective-C

    - (nullable NSNumber *)averageOfProperty:(nonnull NSString *)property;

    Swift

    func average(ofProperty property: String) -> NSNumber?

    Parameters

    property

    The property whose average value should be calculated. Only properties of types int, float, and double are supported.

    Return Value

    The average value of the given property, or nil if the Results are empty.

Freeze

  • Indicates if the collection is frozen.

    Frozen collections are immutable and can be accessed from any thread. The objects read from a frozen collection will also be frozen.

    Declaration

    Objective-C

    @required
    @property (nonatomic, readonly, getter=isFrozen) BOOL frozen;

    Swift

    var isFrozen: Bool { get }
  • Returns a frozen (immutable) snapshot of this collection.

    The frozen copy is an immutable collection which contains the same data as this collection currently contains, but will not update when writes are made to the containing Realm. Unlike live collections, frozen collections can be accessed from any thread.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only.

    Warning

    Holding onto a frozen collection for an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. See RLMRealmConfiguration.maximumNumberOfActiveVersions for more information.

    Declaration

    Objective-C

    - (nonnull instancetype)freeze;

    Swift

    func freeze() -> Self
  • Returns a live version of this frozen collection.

    This method resolves a reference to a live copy of the same frozen collection. If called on a live collection, will return itself.

    Declaration

    Objective-C

    - (nonnull instancetype)thaw;

    Swift

    func thaw() -> Self