Rajeev
Rajeev

Reputation: 5002

Getting distinct rows from Realm table in iOS

I am using Realm database for iOS application where i have a use case in which i want to filter result set by distinct values for a particular field. This field is not a primary key of the realm table.

I was not able to construct query for that.

Sample query :

RLMResults *allFiles = [FileRLMObject objectsInRealm:realmObject where:@"colA == %@", @"test1"];

FileRLMObject is a subclass of RLMObject from realm library

here table contains one column with name colB. While getting allFiles results, i want to get rows which are having distinct colB values.

Any suggestions how i can achieve this?

Upvotes: 3

Views: 857

Answers (1)

marius
marius

Reputation: 7806

Realm doesn't support distinct queries yet. You can subscribe issue #1103 to track progress on that.

As a workaround, you could query for all values for colB first and then select objects for each value of it, as seen below:

 NSArray *values = [FileRLMObject.allObjects valueForKey:"type"];
 NSSet *distinctValues = [NSSet setWithArray:values];
 NSMutableArray *allFiles = [NSMutableArray new];
 for (NSString *colB in distinctValues) {
      // This takes the firstObject.
      // You might want to modify the sort order to make sure
      // you get a certain object in case that there may exist 
      // multiple objects per distinct value.
      FileRLMObject *object = [FileRLMObject objectsWhere:@"colB == ?", colB].firstObject;
      [allFiles appendObject:object];
 }

Upvotes: 2

Related Questions