RLMDictionary

Objective-C

@interface RLMDictionary<RLMKeyType, RLMObjectType> : NSObject <RLMCollection>

Swift

@_nonSendable(_assumed) class RLMDictionary<RLMKeyType, RLMObjectType> : NSObject, RLMCollection where RLMKeyType : AnyObject, RLMObjectType : AnyObject

RLMDictionary is a container type in Realm representing a dynamic collection of key-value pairs.

Unlike NSDictionary, RLMDictionarys hold a single key and value type. This is referred to in these docs as the “type” and “keyType” of the dictionary.

When declaring an RLMDictionary property, the object type and keyType must be marked as conforming to a protocol by the same name as the objects it should contain.

RLM_COLLECTION_TYPE(ObjectType)
...
@property RLMDictionary<NSString *, ObjectType *><RLMString, ObjectType> *objectTypeDictionary;

RLMDictionarys can be queried with the same predicates as RLMObject and RLMResults.

RLMDictionarys cannot be created directly. RLMDictionary properties on RLMObjects are lazily created when accessed, or can be obtained by querying a Realm.

RLMDictionary only supports NSString as a key. Realm disallows the use of . or $ characters within a dictionary key.

Key-Value Observing

RLMDictionary supports dictionary key-value observing on RLMDictionary properties on RLMObject subclasses, and the invalidated property on RLMDictionary instances themselves is key-value observing compliant when the RLMDictionary is attached to a managed RLMObject (RLMDictionarys on unmanaged RLMObjects will never become invalidated).

Properties

  • The number of entries in the dictionary.

    Declaration

    Objective-C

    @property (nonatomic, readonly) NSUInteger count;

    Swift

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

    Declaration

    Objective-C

    @property (nonatomic, readonly) RLMPropertyType type;

    Swift

    var type: RLMPropertyType { get }
  • The type of the key used in this dictionary.

    Declaration

    Objective-C

    @property (nonatomic, readonly) RLMPropertyType keyType;

    Swift

    var keyType: 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 dictionary.

    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 the dictionary. Returns nil for unmanaged dictionary.

    Declaration

    Objective-C

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

    Swift

    var realm: RLMRealm? { get }
  • Indicates if the dictionary can no longer be accessed.

    Declaration

    Objective-C

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

    Swift

    var isInvalidated: Bool { get }
  • Indicates if the dictionary is frozen.

    Frozen dictionaries are immutable and can be accessed from any thread. Frozen dictionaries are created by calling -freeze on a managed live dictionary. Unmanaged dictionaries are never frozen.

    Declaration

    Objective-C

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

    Swift

    var isFrozen: Bool { get }

Accessing Objects from a Dictionary

  • Returns the value associated with a given key.

    @discussion If key does not start with “@”, invokes object(forKey:). If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key.

    Declaration

    Objective-C

    - (nullable id)valueForKey:(nonnull RLMKeyType)key;

    Swift

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

    Parameters

    key

    The name of the property.

    Return Value

    A value associated with a given key or nil.

  • Returns an array containing the dictionary’s keys.

    Note

    The order of the elements in the array is not defined.

    Declaration

    Objective-C

    @property (copy, readonly) NSArray<RLMKeyType> *_Nonnull allKeys;

    Swift

    var allKeys: [RLMKeyType] { get }
  • Returns an array containing the dictionary’s values.

    Note

    The order of the elements in the array is not defined.

    Declaration

    Objective-C

    @property (copy, readonly) NSArray<RLMObjectType> *_Nonnull allValues;

    Swift

    var allValues: [RLMObjectType] { get }
  • Returns the value associated with a given key.

    Note

    nil will be returned if no value is associated with a given key. NSNull will be returned where null is associated with the key.

    Declaration

    Objective-C

    - (nullable RLMObjectType)objectForKey:(nonnull RLMKeyType)key;

    Swift

    func object(forKey key: RLMKeyType) -> RLMObjectType?

    Parameters

    key

    The key for which to return the corresponding value.

    Return Value

    The value associated with key.

  • Returns the value associated with a given key.

    Note

    nil will be returned if no value is associated with a given key. NSNull will be returned where null is associated with the key.

    Declaration

    Objective-C

    - (nullable RLMObjectType)objectForKeyedSubscript:(nonnull RLMKeyType)key;

    Swift

    subscript(key: RLMKeyType) -> RLMObjectType? { get set }

    Parameters

    key

    The key for which to return the corresponding value.

    Return Value

    The value associated with key.

  • Applies a given block object to the each key-value pair of the dictionary.

    Note

    If the block sets *stop to YES, the enumeration stops.

    Declaration

    Objective-C

    - (void)enumerateKeysAndObjectsUsingBlock:
        (nonnull void (^)(RLMKeyType _Nonnull, RLMObjectType _Nonnull,
                          BOOL *_Nonnull))block;

    Swift

    func enumerateKeysAndObjects(_ block: @escaping (RLMKeyType, RLMObjectType, UnsafeMutablePointer<ObjCBool>) -> Void)

    Parameters

    block

    A block object to operate on entries in the dictionary.

Adding, Removing, and Replacing Objects in a Dictionary

  • Replace the contents of a dictionary with the contents of another dictionary - NSDictionary or RLMDictionary.

    This will remove all elements in this dictionary and then apply each element from the given dictionary.

    Warning

    This method may only be called during a write transaction.

    Warning

    If otherDictionary is self this will result in an empty dictionary.

    Declaration

    Objective-C

    - (void)setDictionary:(nonnull id)otherDictionary;

    Swift

    func setDictionary(_ otherDictionary: Any)
  • Removes all contents in the dictionary.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)removeAllObjects;

    Swift

    func removeAllObjects()
  • Removes from the dictionary entries specified by elements in a given array. If a given key does not exist, no mutation will happen for that key.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)removeObjectsForKeys:(nonnull NSArray<RLMKeyType> *)keyArray;

    Swift

    func removeObjects(forKeys keyArray: [RLMKeyType])
  • Removes a given key and its associated value from the dictionary. If the key does not exist the dictionary will not be modified.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)removeObjectForKey:(nonnull RLMKeyType)key;

    Swift

    func removeObject(forKey key: RLMKeyType)
  • Adds a given key-value pair to the dictionary if the key is not present, or updates the value for the given key if the key already present.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)setObject:(nullable RLMObjectType)obj
        forKeyedSubscript:(nonnull RLMKeyType)key;
  • Adds a given key-value pair to the dictionary if the key is not present, or updates the value for the given key if the key already present.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)setObject:(nullable RLMObjectType)anObject
               forKey:(nonnull RLMKeyType)aKey;

    Swift

    func setObject(_ anObject: RLMObjectType?, forKey aKey: RLMKeyType)
  • Adds to the receiving dictionary the entries from another dictionary.

    Note

    If the receiving dictionary contains the same key(s) as the otherDictionary, then the receiving dictionary will update each key-value pair for the matching key.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Objective-C

    - (void)addEntriesFromDictionary:(nonnull id<NSFastEnumeration>)otherDictionary;

    Swift

    func addEntries(fromDictionary otherDictionary: any NSFastEnumeration)

    Parameters

    otherDictionary

    An enumerable object such as NSDictionary or RLMDictionary which contains objects of the same type as the receiving dictionary.

Querying a Dictionary

  • Returns all the values matching the given predicate in the dictionary.

    Note

    The keys in the dictionary are ignored when quering values, and they will not be returned in the RLMResults.

    Declaration

    Objective-C

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

    Parameters

    predicateFormat

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

    Return Value

    An RLMResults of objects that match the given predicate.

  • Returns all the values matching the given predicate in the dictionary.

    Note

    The keys in the dictionary are ignored when quering values, and they will not be returned in the RLMResults.

    Declaration

    Objective-C

    - (nonnull RLMResults<RLMObjectType> *)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 of objects that match the given predicate

  • Returns a sorted RLMResults of all values in the dictionary.

    Note

    The keys in the dictionary are ignored when sorting values, and they will not be returned in the RLMResults.

    Declaration

    Objective-C

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

    Swift

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

    Parameters

    keyPath

    The key path to sort by.

    ascending

    The direction to sort in.

    Return Value

    An RLMResults sorted by the specified key path.

  • Returns a sorted RLMResults of all values in the dictionary.

    Note

    The keys in the dictionary are ignored when sorting values, and they will not be returned in the RLMResults.

    Declaration

    Objective-C

    - (nonnull RLMResults<RLMObjectType> *)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 all values in the dictionary.

    Note

    The keys in the dictionary are ignored, and they will not be returned in the RLMResults.

    Declaration

    Objective-C

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

    Swift

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

    Parameters

    keyPaths

    The key paths to distinct on.

    Return Value

    An RLMResults with the distinct values of the keypath(s).

Aggregating Property Values

  • Returns the minimum (lowest) value of the given property among all the values in the dictionary.

    NSNumber *min = [object.dictionaryProperty minOfProperty:@"age"];
    

    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, NSDate, RLMValue and RLMDecimal128 are supported.

    Return Value

    The minimum value of the property, or nil if the dictionary is empty.

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

    NSNumber *max = [object.dictionaryProperty maxOfProperty:@"age"];
    

    Declaration

    Objective-C

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

    Swift

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

    Parameters

    property

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

    Return Value

    The maximum value of the property, or nil if the dictionary is empty.

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

    NSNumber *sum = [object.dictionaryProperty sumOfProperty:@"age"];
    

    Declaration

    Objective-C

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

    Swift

    func sum(ofProperty property: String) -> NSNumber

    Parameters

    property

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

    Return Value

    The sum of the given property.

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

    NSNumber *average = [object.dictionaryProperty averageOfProperty:@"age"];
    

    Declaration

    Objective-C

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

    Swift

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

    Parameters

    property

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

    Return Value

    The average value of the given property, or nil if the dictionary is empty.

Notifications

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

    The block will be asynchronously called with the initial dictionary, and then called again after each write transaction which changes any of the keys or values within the dictionary.

    The changes parameter will be nil the first time the block is called. For each call after that, it will contain information about which keys in the dictionary were added, modified or deleted. If a write transaction did not modify any keys or values in the dictionary, the block is not called at all.

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

    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.

    Person *person = [[Person allObjectsInRealm:realm] firstObject];
    NSLog(@"person.dogs.count: %zu", person.dogs.count); // => 0
    self.token = [person.dogs addNotificationBlock(RLMDictionary<NSString *, Dog *><RLMString, Dog> *dogs,
                                      RLMDictionaryChange *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";
        person.dogs[@"frenchBulldog"] = 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.

    Warning

    This method may only be called on a non-frozen managed dictionary.

    Declaration

    Objective-C

    - (nonnull RLMNotificationToken *)addNotificationBlock:
        (nonnull void (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable,
                          RLMDictionaryChange *_Nullable, NSError *_Nullable))block;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMDictionary<RLMKeyType, RLMObjectType>?, RLMDictionaryChange?, (any Error)?) -> Void) -> RLMNotificationToken

    Parameters

    block

    The block to be called each time the dictionary changes.

    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 dictionary changes.

    The block will be asynchronously called with the initial dictionary, and then called again after each write transaction which changes any of the key-value in the dictionary or which objects are in the results.

    The changes parameter will be nil the first time the block is called. For each call after that, it will contain information about which keys in the dictionary were added or modified. If a write transaction did not modify any objects in the dictionary, the block is not called at all.

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

    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 (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable,
                              RLMDictionaryChange *_Nullable,
                              NSError *_Nullable))block
                       queue:(nullable dispatch_queue_t)queue;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMDictionary<RLMKeyType, RLMObjectType>?, RLMDictionaryChange?, (any Error)?) -> Void, queue: dispatch_queue_t?) -> 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 dictionary changes.

    The block will be asynchronously called with the initial dictionary, and then called again after each write transaction which changes any of the key-value in the dictionary or which objects are in the results.

    The changes parameter will be nil the first time the block is called. For each call after that, it will contain information about which keys in the dictionary were added or modified. If a write transaction did not modify any objects in the dictionary, the block is not called at all.

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

    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 (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable,
                              RLMDictionaryChange *_Nullable,
                              NSError *_Nullable))block
                    keyPaths:(nullable NSArray<NSString *> *)keyPaths
                       queue:(nullable dispatch_queue_t)queue;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMDictionary<RLMKeyType, RLMObjectType>?, RLMDictionaryChange?, (any Error)?) -> Void, keyPaths: [String]?, queue: dispatch_queue_t?) -> RLMNotificationToken

    Parameters

    block

    The block to be called whenever a change occurs.

    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.

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

    The block will be asynchronously called with the initial dictionary, and then called again after each write transaction which changes any of the key-value in the dictionary or which objects are in the results.

    The changes parameter will be nil the first time the block is called. For each call after that, it will contain information about which keys in the dictionary were added or modified. If a write transaction did not modify any objects in the dictionary, the block is not called at all.

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

    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 (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable,
                              RLMDictionaryChange *_Nullable,
                              NSError *_Nullable))block
                    keyPaths:(nullable NSArray<NSString *> *)keyPaths;

    Swift

    func addNotificationBlock(_ block: @escaping (RLMDictionary<RLMKeyType, RLMObjectType>?, RLMDictionaryChange?, (any Error)?) -> Void, keyPaths: [String]?) -> RLMNotificationToken

    Parameters

    block

    The block to be called whenever a change occurs.

    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.

Freeze

  • Returns a frozen (immutable) snapshot of a dictionary.

    The frozen copy is an immutable dictionary which contains the same data as this dictionary currently contains, but will not update when writes are made to the containing Realm. Unlike live dictionaries, frozen dictionaries 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

    This method may only be called on a managed dictionary.

    Warning

    Holding onto a frozen dictionary 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

Unavailable Methods

  • Unavailable

    RLMDictionary cannot be created directly

    -[RLMDictionary init] is not available because RLMDictionarys cannot be created directly. RLMDictionary properties on RLMObjects are lazily created when accessed.

    Declaration

    Objective-C

    - (nonnull instancetype)init;
  • Unavailable

    RLMDictionary cannot be created directly

    +[RLMDictionary new] is not available because RLMDictionarys cannot be created directly. RLMDictionary properties on RLMObjects are lazily created when accessed.

    Declaration

    Objective-C

    + (nonnull instancetype)new;