Return unique/distinct values with Realm query

匿名 (未验证) 提交于 2019-12-03 08:42:37

问题:

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.

回答1:

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


回答2:

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)     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!