RLMObject

@interface RLMObject : RLMObjectBase <RLMThreadConfined>

RLMObject is a base class for model objects representing data stored in Realms.

Define your model classes by subclassing RLMObject and adding properties to be managed. Then instantiate and use your custom subclasses instead of using the RLMObject class directly.

// Dog.h
@interface Dog : RLMObject
@property NSString *name;
@property BOOL      adopted;
@end

// Dog.m
@implementation Dog
@end //none needed

Supported property types

  • NSString
  • NSInteger, int, long, float, and double
  • BOOL or bool
  • NSDate
  • NSData
  • NSNumber<X>, where X is one of RLMInt, RLMFloat, RLMDouble or RLMBool, for optional number properties
  • RLMObject subclasses, to model many-to-one relationships.
  • RLMArray<X>, where X is an RLMObject subclass, to model many-to-many relationships.

Querying

You can initiate queries directly via the class methods: allObjects, objectsWhere:, and objectsWithPredicate:. These methods allow you to easily query a custom subclass for instances of that class in the default Realm.

To search in a Realm other than the default Realm, use the allObjectsInRealm:, objectsInRealm:where:, and objectsInRealm:withPredicate: class methods.

See

RLMRealm

Relationships

See our Cocoa guide for more details.

Key-Value Observing

All RLMObject properties (including properties you create in subclasses) are Key-Value Observing compliant, except for realm and objectSchema.

Keep the following tips in mind when observing Realm objects:

  1. Unlike NSMutableArray properties, RLMArray properties do not require using the proxy object returned from -mutableArrayValueForKey:, or defining KVC mutation methods on the containing class. You can simply call methods on the RLMArray directly; any changes will be automatically observed by the containing object.
  2. Unmanaged RLMObject instances cannot be added to a Realm while they have any observed properties.
  3. Modifying managed RLMObjects within -observeValueForKeyPath:ofObject:change:context: is not recommended. Properties may change even when the Realm is not in a write transaction (for example, when -[RLMRealm refresh] is called after changes are made on a different thread), and notifications sent prior to the change being applied (when NSKeyValueObservingOptionPrior is used) may be sent at times when you cannot begin a write transaction.
  • Creates an unmanaged instance of a Realm object.

    Call addObject: on an RLMRealm instance to add an unmanaged object into that Realm.

    See

    [RLMRealm addObject:]

    Declaration

    Objective-C

    - (nonnull instancetype)init;

    Swift

    init()
  • Creates an unmanaged instance of a Realm object.

    Pass in an NSArray or NSDictionary instance to set the values of the object’s properties.

    Call addObject: on an RLMRealm instance to add an unmanaged object into that Realm.

    See

    [RLMRealm addObject:]

    Declaration

    Objective-C

    - (nonnull instancetype)initWithValue:(nonnull id)value;

    Swift

    convenience init(value: Any)
  • Returns the class name for a Realm object subclass.

    Warning

    Do not override. Realm relies on this method returning the exact class name.

    Declaration

    Objective-C

    + (nonnull NSString *)className;

    Swift

    class func className() -> String

    Return Value

    The class name for the model class.

  • Creates an instance of a Realm object with a given value, and adds it to the default Realm.

    If nested objects are included in the argument, createInDefaultRealmWithValue: will be recursively called on them.

    The value argument can be a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an array containing one element for each managed property.

    An exception will be thrown if any required properties are not present and those properties were not defined with default values.

    If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    See

    defaultPropertyValues

    Declaration

    Objective-C

    + (nonnull instancetype)createInDefaultRealmWithValue:(nonnull id)value;

    Swift

    class func createInDefaultRealm(withValue value: Any) -> Self

    Parameters

    value

    The value used to populate the object.

  • Creates an instance of a Realm object with a given value, and adds it to the specified Realm.

    If nested objects are included in the argument, createInRealm:withValue: will be recursively called on them.

    The value argument can be a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an array containing one element for each managed property.

    An exception will be thrown if any required properties are not present and those properties were not defined with default values.

    If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    See

    defaultPropertyValues

    Declaration

    Objective-C

    + (nonnull instancetype)createInRealm:(nonnull RLMRealm *)realm
                                withValue:(nonnull id)value;

    Swift

    class func create(in realm: RLMRealm, withValue value: Any) -> Self

    Parameters

    realm

    The Realm which should manage the newly-created object.

    value

    The value used to populate the object.

  • Creates or updates a Realm object within the default Realm.

    This method may only be called on Realm object types with a primary key defined. If there is already an object with the same primary key value in the default Realm, its values are updated and the object is returned. Otherwise, this method creates and populates a new instance of the object in the default Realm.

    If nested objects are included in the argument, createOrUpdateInDefaultRealmWithValue: will be recursively called on them if they have primary keys, createInDefaultRealmWithValue: if they do not.

    The value argument is used to populate the object. It can be a Realm object, a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an array containing one element for each managed property.

    If the object is being created, an exception will be thrown if any required properties are not present and those properties were not defined with default values.

    If the value argument is a Realm object already managed by the default Realm, the argument’s type is the same as the receiver, and the objects have identical values for their managed properties, this method does nothing.

    If the object is being updated, each property defined in its schema will be set by copying from value using key-value coding. If the value argument does not respond to valueForKey: for a given property name (or getter name, if defined), that value will remain untouched. Nullable properties on the object can be set to nil by using NSNull as the updated value. Each property is set even if the existing value is the same as the new value being set, and notifications will report them all being changed. See createOrUpdateModifiedInDefaultRealmWithValue: for a version of this function which only sets the values which have changed.

    If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    See

    defaultPropertyValues, primaryKey

    Declaration

    Objective-C

    + (nonnull instancetype)createOrUpdateInDefaultRealmWithValue:(nonnull id)value;

    Swift

    class func createOrUpdateInDefaultRealm(withValue value: Any) -> Self

    Parameters

    value

    The value used to populate the object.

  • Creates or updates a Realm object within the default Realm.

    This method may only be called on Realm object types with a primary key defined. If there is already an object with the same primary key value in the default Realm, its values are updated and the object is returned. Otherwise, this method creates and populates a new instance of the object in the default Realm.

    If nested objects are included in the argument, createOrUpdateModifiedInDefaultRealmWithValue: will be recursively called on them if they have primary keys, createInDefaultRealmWithValue: if they do not.

    The value argument is used to populate the object. It can be a Realm object, a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an array containing one element for each managed property.

    If the object is being created, an exception will be thrown if any required properties are not present and those properties were not defined with default values.

    If the value argument is a Realm object already managed by the default Realm, the argument’s type is the same as the receiver, and the objects have identical values for their managed properties, this method does nothing.

    If the object is being updated, each property defined in its schema will be set by copying from value using key-value coding. If the value argument does not respond to valueForKey: for a given property name (or getter name, if defined), that value will remain untouched. Nullable properties on the object can be set to nil by using NSNull as the updated value. Unlike createOrUpdateInDefaultRealmWithValue:, only properties which have changed in value are set, and any change notifications produced by this call will report only which properies have actually changed.

    Checking which properties have changed imposes a small amount of overhead, and so this method may be slower when all or nearly all of the properties being set have changed. If most or all of the properties being set have not changed, this method will be much faster than unconditionally setting all of them, and will also reduce how much data has to be written to the Realm, saving both i/o time and disk space.

    If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    See

    defaultPropertyValues, primaryKey

    Declaration

    Objective-C

    + (nonnull instancetype)createOrUpdateModifiedInDefaultRealmWithValue:
        (nonnull id)value;

    Swift

    class func createOrUpdateModifiedInDefaultRealm(withValue value: Any) -> Self

    Parameters

    value

    The value used to populate the object.

  • Creates or updates an Realm object within a specified Realm.

    This method may only be called on Realm object types with a primary key defined. If there is already an object with the same primary key value in the given Realm, its values are updated and the object is returned. Otherwise this method creates and populates a new instance of this object in the given Realm.

    If nested objects are included in the argument, createOrUpdateInRealm:withValue: will be recursively called on them if they have primary keys, createInRealm:withValue: if they do not.

    The value argument is used to populate the object. It can be a Realm object, a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an array containing one element for each managed property.

    If the object is being created, an exception will be thrown if any required properties are not present and those properties were not defined with default values.

    If the value argument is a Realm object already managed by the given Realm, the argument’s type is the same as the receiver, and the objects have identical values for their managed properties, this method does nothing.

    If the object is being updated, each property defined in its schema will be set by copying from value using key-value coding. If the value argument does not respond to valueForKey: for a given property name (or getter name, if defined), that value will remain untouched. Nullable properties on the object can be set to nil by using NSNull as the updated value. Each property is set even if the existing value is the same as the new value being set, and notifications will report them all being changed. See createOrUpdateModifiedInRealm:withValue: for a version of this function which only sets the values which have changed.

    If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    See

    defaultPropertyValues, primaryKey

    Declaration

    Objective-C

    + (nonnull instancetype)createOrUpdateInRealm:(nonnull RLMRealm *)realm
                                        withValue:(nonnull id)value;

    Swift

    class func createOrUpdate(in realm: RLMRealm, withValue value: Any) -> Self

    Parameters

    realm

    The Realm which should own the object.

    value

    The value used to populate the object.

  • Creates or updates an Realm object within a specified Realm.

    This method may only be called on Realm object types with a primary key defined. If there is already an object with the same primary key value in the given Realm, its values are updated and the object is returned. Otherwise this method creates and populates a new instance of this object in the given Realm.

    If nested objects are included in the argument, createOrUpdateInRealm:withValue: will be recursively called on them if they have primary keys, createInRealm:withValue: if they do not.

    The value argument is used to populate the object. It can be a Realm object, a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an array containing one element for each managed property.

    If the object is being created, an exception will be thrown if any required properties are not present and those properties were not defined with default values.

    If the value argument is a Realm object already managed by the given Realm, the argument’s type is the same as the receiver, and the objects have identical values for their managed properties, this method does nothing.

    If the object is being updated, each property defined in its schema will be set by copying from value using key-value coding. If the value argument does not respond to valueForKey: for a given property name (or getter name, if defined), that value will remain untouched. Nullable properties on the object can be set to nil by using NSNull as the updated value. Unlike createOrUpdateInRealm:withValue:, only properties which have changed in value are set, and any change notifications produced by this call will report only which properies have actually changed.

    Checking which properties have changed imposes a small amount of overhead, and so this method may be slower when all or nearly all of the properties being set have changed. If most or all of the properties being set have not changed, this method will be much faster than unconditionally setting all of them, and will also reduce how much data has to be written to the Realm, saving both i/o time and disk space.

    If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    See

    defaultPropertyValues, primaryKey

    Declaration

    Objective-C

    + (nonnull instancetype)createOrUpdateModifiedInRealm:(nonnull RLMRealm *)realm
                                                withValue:(nonnull id)value;

    Swift

    class func createOrUpdateModified(in realm: RLMRealm, withValue value: Any) -> Self

    Parameters

    realm

    The Realm which should own the object.

    value

    The value used to populate the object.

  • The Realm which manages the object, or nil if the object is unmanaged.

    Declaration

    Objective-C

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

    Swift

    var realm: RLMRealm? { get }
  • The object schema which lists the managed properties for the object.

    Declaration

    Objective-C

    @property (readonly, nonatomic) RLMObjectSchema *_Nonnull objectSchema;

    Swift

    var objectSchema: RLMObjectSchema { get }
  • Indicates if the object can no longer be accessed because it is now invalid.

    An object can no longer be accessed if the object has been deleted from the Realm that manages it, or if invalidate is called on that Realm.

    Declaration

    Objective-C

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

    Swift

    var isInvalidated: Bool { get }
  • Indicates if this object is frozen.

    Declaration

    Objective-C

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

    Swift

    var isFrozen: Bool { get }
  • Returns an array of property names for properties which should be indexed.

    Only string, integer, boolean, and NSDate properties are supported.

    Declaration

    Objective-C

    + (nonnull NSArray<NSString *> *)indexedProperties;

    Swift

    class func indexedProperties() -> [String]

    Return Value

    An array of property names.

  • Override this method to specify the default values to be used for each property.

    Declaration

    Objective-C

    + (nullable NSDictionary *)defaultPropertyValues;

    Swift

    class func defaultPropertyValues() -> [AnyHashable : Any]?

    Return Value

    A dictionary mapping property names to their default values.

  • Override this method to specify the name of a property to be used as the primary key.

    Only properties of types RLMPropertyTypeString and RLMPropertyTypeInt can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set, which incurs minor overhead. Indexes are created automatically for primary key properties.

    Declaration

    Objective-C

    + (nullable NSString *)primaryKey;

    Swift

    class func primaryKey() -> String?

    Return Value

    The name of the property designated as the primary key.

  • Override this method to specify the names of properties to ignore. These properties will not be managed by the Realm that manages the object.

    Declaration

    Objective-C

    + (nullable NSArray<NSString *> *)ignoredProperties;

    Swift

    class func ignoredProperties() -> [String]?

    Return Value

    An array of property names to ignore.

  • Override this method to specify the names of properties that are non-optional (i.e. cannot be assigned a nil value).

    By default, all properties of a type whose values can be set to nil are considered optional properties. To require that an object in a Realm always store a non-nil value for a property, add the name of the property to the array returned from this method.

    Properties of RLMObject type cannot be non-optional. Array and NSNumber properties can be non-optional, but there is no reason to do so: arrays do not support storing nil, and if you want a non-optional number you should instead use the primitive type.

    Declaration

    Objective-C

    + (nonnull NSArray<NSString *> *)requiredProperties;

    Swift

    class func requiredProperties() -> [String]

    Return Value

    An array of property names that are required.

  • Override this method to provide information related to properties containing linking objects.

    Each property of type RLMLinkingObjects must have a key in the dictionary returned by this method consisting of the property name. The corresponding value must be an instance of RLMPropertyDescriptor that describes the class and property that the property is linked to.

    return @{ @"owners": [RLMPropertyDescriptor descriptorWithClass:Owner.class propertyName:@"dogs"] };
    

    Declaration

    Objective-C

    + (nonnull NSDictionary<NSString *, RLMPropertyDescriptor *> *)
        linkingObjectsProperties;

    Swift

    class func linkingObjectsProperties() -> [String : RLMPropertyDescriptor]

    Return Value

    A dictionary mapping property names to RLMPropertyDescriptor instances.

  • Returns all objects of this object type from the default Realm.

    Declaration

    Objective-C

    + (nonnull RLMResults *)allObjects;

    Swift

    class func allObjects() -> RLMResults

    Return Value

    An RLMResults containing all objects of this type in the default Realm.

  • Returns all objects of this object type matching the given predicate from the default Realm.

    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 all objects of this type in the default Realm that match the given predicate.

  • Returns all objects of this object type matching the given predicate from the default Realm.

    Declaration

    Objective-C

    + (nonnull RLMResults *)objectsWithPredicate:(nullable NSPredicate *)predicate;

    Swift

    class func objects(with predicate: NSPredicate?) -> RLMResults

    Parameters

    predicate

    The predicate with which to filter the objects.

    Return Value

    An RLMResults containing all objects of this type in the default Realm that match the given predicate.

  • Retrieves the single instance of this object type with the given primary key from the default Realm.

    Returns the object from the default Realm which has the given primary key, or nil if the object does not exist. This is slightly faster than the otherwise equivalent [[SubclassName objectsWhere:@"primaryKeyPropertyName = %@", key] firstObject].

    This method requires that primaryKey be overridden on the receiving subclass.

    See

    -primaryKey

    Declaration

    Objective-C

    + (nullable instancetype)objectForPrimaryKey:(nullable id)primaryKey;

    Swift

    class func object(forPrimaryKey primaryKey: Any?) -> Self?

    Return Value

    An object of this object type, or nil if an object with the given primary key does not exist.

  • Returns all objects of this object type from the specified Realm.

    Declaration

    Objective-C

    + (nonnull RLMResults *)allObjectsInRealm:(nonnull RLMRealm *)realm;

    Swift

    class func allObjects(in realm: RLMRealm) -> RLMResults

    Parameters

    realm

    The Realm to query.

    Return Value

    An RLMResults containing all objects of this type in the specified Realm.

  • Returns all objects of this object type matching the given predicate from the specified Realm.

    Declaration

    Objective-C

    + (nonnull RLMResults *)objectsInRealm:(nonnull RLMRealm *)realm
                                     where:(nonnull NSString *)predicateFormat, ...;

    Parameters

    predicateFormat

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

    realm

    The Realm to query.

    Return Value

    An RLMResults containing all objects of this type in the specified Realm that match the given predicate.

  • Returns all objects of this object type matching the given predicate from the specified Realm.

    Declaration

    Objective-C

    + (nonnull RLMResults *)objectsInRealm:(nonnull RLMRealm *)realm
                             withPredicate:(nullable NSPredicate *)predicate;

    Swift

    class func objects(in realm: RLMRealm, with predicate: NSPredicate?) -> RLMResults

    Parameters

    predicate

    A predicate to use to filter the elements.

    realm

    The Realm to query.

    Return Value

    An RLMResults containing all objects of this type in the specified Realm that match the given predicate.

  • Retrieves the single instance of this object type with the given primary key from the specified Realm.

    Returns the object from the specified Realm which has the given primary key, or nil if the object does not exist. This is slightly faster than the otherwise equivalent [[SubclassName objectsInRealm:realm where:@"primaryKeyPropertyName = %@", key] firstObject].

    This method requires that primaryKey be overridden on the receiving subclass.

    See

    -primaryKey

    Declaration

    Objective-C

    + (nullable instancetype)objectInRealm:(nonnull RLMRealm *)realm
                             forPrimaryKey:(nullable id)primaryKey;

    Swift

    class func object(in realm: RLMRealm, forPrimaryKey primaryKey: Any?) -> Self?

    Return Value

    An object of this object type, or nil if an object with the given primary key does not exist.

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

    The block will be asynchronously called after each write transaction which deletes the object or modifies any of the managed properties of the object, including self-assignments that set a property to its existing value.

    For write transactions performed on different threads or in different processes, the block will be called when the managing Realm is (auto)refreshed to a version including the changes, while for local write transactions it will be called at some point in the future after the write transaction is committed.

    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.

    Unlike with RLMArray and RLMResults, there is no initial callback made after you add a new notification block.

    Only objects which are managed by a Realm can be observed in this way. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call -invalidate on the token.

    It is safe to capture a strong reference to the observed object within the callback block. There is no retain cycle due to that the callback is retained by the returned token and not by the object itself.

    Warning

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

    Declaration

    Objective-C

    - (nonnull RLMNotificationToken *)addNotificationBlock:
        (nonnull RLMObjectChangeBlock)block;

    Swift

    func addNotificationBlock(_ block: @escaping RLMObjectChangeBlock) -> 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 object changes.

    The block will be asynchronously called after each write transaction which deletes the object or modifies any of the managed properties of the object, including self-assignments that set a property to its existing value.

    For write transactions performed on different threads or in different processes, the block will be called when the managing Realm is (auto)refreshed to a version including the changes, while for local write transactions it will be called at some point in the future after the write transaction is committed.

    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.

    Unlike with RLMArray and RLMResults, there is no initial callback made after you add a new notification block.

    Only objects which are managed by a Realm can be observed in this way. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call -invalidate on the token.

    It is safe to capture a strong reference to the observed object within the callback block. There is no retain cycle due to that the callback is retained by the returned token and not by the object itself.

    Warning

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

    Warning

    The queue must be a serial queue.

    Declaration

    Objective-C

    - (nonnull RLMNotificationToken *)
        addNotificationBlock:(nonnull RLMObjectChangeBlock)block
                       queue:(nonnull dispatch_queue_t)queue;

    Swift

    func addNotificationBlock(_ block: @escaping RLMObjectChangeBlock, 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.

  • Returns YES if another Realm object instance points to the same object as the receiver in the Realm managing the receiver.

    For frozen objects and object types with a primary key, isEqual: is overridden to use the same logic as this method (along with a corresponding implementation for hash). Non-frozen objects without primary keys use pointer identity for isEqual: and hash.

    Declaration

    Objective-C

    - (BOOL)isEqualToObject:(nonnull RLMObject *)object;

    Swift

    func isEqual(to object: RLMObject) -> Bool

    Parameters

    object

    The object to compare the receiver to.

    Return Value

    Whether the object represents the same object as the receiver.

  • Returns a frozen (immutable) snapshot of this object.

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

    Warning

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

    Warning

    This method can only be called on a managed object.

    Declaration

    Objective-C

    - (nonnull instancetype)freeze;

    Swift

    func freeze() -> Self