Return unique / different values ​​using Realm query

I have a Message/RLMObject model that has the NSString *jabberID property / string, and I want to get every unique value inside that string.

In other words, I want to get non-duplicate jabberID values ​​from my Message model. Can anyone help figure this out?

The way I do this with coredata used the returnsDistinctResults parameter on NSFetchRequest .

+7
ios objective-c swift realm
source share
2 answers

I found out that Realm does not support completely different requests. The good news is that I found a workaround for 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) } } 
+6
source share

A functional approach to programming, since Swift has this, and Realm is lazy; Not so simple / accessible solution in Objective-C, but for Swift at least: Swift

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

UPDATED:

A quick reduction is a kind of performance intensity, allocating a bunch of intermediate arrays, instead the following should be much better, but should be explicitly stripped

 let distinctTypes = Array(Set(Realm().objects(User).valueForKey("type") as! [String])) 
+12
source share

All Articles