Search code examples
iosobjective-crecursionrealmrelationships

Recursive Relationship in Realm Model


If I wish to have a Realm array of the same user model, an exception occurs. RLMException(@"RLMArray properties require a protocol defining the contained type - example: RLMArray<Person>."); So is there a workaround? How can a recursive relationship be implemented in Realm as below?

#import <Realm/Realm.h>
@interface User : RLMObject
@property NSInteger userId;
@property NSString *displayName;
@property RLMArray<User> *friends;
- (instancetype)initWithDictionary:(NSDictionary *)data;
@end  
RLM_ARRAY_TYPE (User)

Solution

  • As the exception says, you need to declare a protocol to define the contained type of the RLMArray. This is what the RLM_ARRAY_TYPE macro does. The special thing here is that you need to put this declaration before your interface declaration, which can be done by pre-declaring the User type with @class. You can do it like this :

    #import <Realm/Realm.h>
    
    @class User;
    RLM_ARRAY_TYPE (User)
    
    @interface User : RLMObject
    @property NSInteger userId;
    @property NSString *displayName;
    @property RLMArray<User> *friends;
    - (instancetype)initWithDictionary:(NSDictionary *)data;
    @end