Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return unique/distinct values with Realm query

I have a Message/RLMObject model that has a NSString *jabberID property/row and I want to retrieve every unique value inside that row.

In other word, I want to retrieve non-repeated jabberID values from my Message model. Can anyone help out figuring this?

The way I use to do with coredata was using returnsDistinctResults setting on the NSFetchRequest.

like image 426
Marcos Curvello Avatar asked May 14 '15 19:05

Marcos Curvello


2 Answers

Functional programming approach since Swift has it, and Realm lazy loads; Not as easy/available a solution in Objective-C but for Swift at least: Swift

let distinctTypes = reduce(Realm().objects(User), []) { $0 + (!contains($0, $1.type) ? [$1.type] : [] ) }

UPDATED:

Swift reduce is kind of a performance intensive, allocating a bunch of intermediate array's, instead the following should be much better performance wise, but must be explicitly cast

let distinctTypes = Array(Set(Realm().objects(User).valueForKey("type") as! [String]))
like image 192
apocolipse Avatar answered Nov 14 '22 00:11

apocolipse


I found out Realm doesn't fully support distinct queries yet. The good news is I also found a workaround for it, on this github issue.

Objective-c

RLMResults *messages = [Message allObjects];
NSMutableArray *uniqueIDs = [[NSMutableArray alloc] init];
NSMutableArray *uniqueMessages  = [[NSMutableArray alloc] init];
for (Message *msg in messages) {
    NSString *jabberID = msg.jabberID;
    Message *uniqueMSG = (Message *)msg;
    if (![uniqueIDs containsObject:jabberID]) {
        [uniqueMessages addObject:uniqueMSG];
        [uniqueIDs addObject:jabberID];
    }
}

Swift 3.0

let realm = try! Realm()
let distinctIDs = Set(realm.objects(Message.self).value(forKey: "jabberID") as! [String])
var distinctMessages = [Message]()
for jabberID in distinctIDs {
    if let message = realm.objects(Message.self).filter("jabberID = '\(jabberID)'").first {
        distinctMessages.append(message)
    }
}
like image 25
Marcos Curvello Avatar answered Nov 14 '22 00:11

Marcos Curvello