realm db, get parent link of object

405 views Asked by At

I have the following object created with Realm.io. A simple folder, with nested subfolders

when i call subFolders, i simply get all the subfolders, working like a charm. But if i fetch a subfolder, how do i get the parent folder of a that object? aka, navigate back ..

    RLM_ARRAY_TYPE(Folder)

    @interface Folder : RLMObject
      @property (nonatomic, strong)  NSString *name;
      @property RLMArray *subFolders;
   @end

   ...
   ...
   ...

   [folder.subFolders addObject:subFolder];

2

There are 2 answers

1
lostInTransit On

You will have to have a relation between the Folder and SubFolder objects. Assuming SubFolder is an RLMObject, have a folderId property within the object. This will let you get the Folder for a SubFolder. This would act just like a foreign key in a relational database.

0
Thomas Goyne On

[obj linkingObjectsOfClass:@"Folder" forProperty:@"subFolders"] will give you an array of all Folder objects whose subFolders array contains obj. If you know that there will only ever be one and want a convenient property to access it from, you can do something like the following to be able to do folder.parentFolder:

@property (nonatomic, readonly) Folder *parentFolder;
...
- (Folder *)parentFolder {
    return [obj linkingObjectsOfClass:@"Folder" forProperty:@"subFolders"].firstObject;
}