问题描述
我有一个 Message / RLMObject
模型,它有一个 NSString * jabberID
属性/行,我想要检索该行中的每个唯一
值。
I have a Message/RLMObject
model that has a NSString *jabberID
property/row and I want to retrieve every unique
value inside that row.
换句话说,我想从我的消息中检索未重复的
型号。任何人都可以帮忙解决这个问题吗? jabberID
值
In other word, I want to retrieve non-repeated jabberID
values from my Message
model. Can anyone help out figuring this?
我使用coredata的方式是在 NSFetchRequest returnsDistinctResults
设置/ code>。
The way I use to do with coredata was using returnsDistinctResults
setting on the NSFetchRequest
.
推荐答案
我发现Realm还没有完全支持不同的查询。好消息是我在这个上找到了解决方法。 。
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)
}
}
这篇关于使用Realm查询返回唯一/不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!