8

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.

2 Answers 2

13

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]))
6

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)
    }
}
4
  • Does allObjects return a Results collection? Commented Aug 6, 2016 at 7:19
  • 1
    Yes, it will return a Results collection of all the objects. Commented Aug 15, 2016 at 20:04
  • I see, then this approach will loose the lazy evaluation from Results. Commented Aug 16, 2016 at 9:13
  • you shoud use a set to check membership, is much faster Commented Mar 3, 2019 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.