可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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) } }