How to get unique value from Realm database in swift

I am using a news application in swift using Realm database . My database has the same news categories. How to get unique value from Realm database ? I am using a primary key

 class News: Object { dynamic var newsID: String = "" dynamic var newsTitle: String = "" dynamic var newsFullText: String = "" dynamic var newsImage: String = "" dynamic var newsAutor: String = "" dynamic var newsCommentCount: String = "" dynamic var newsSeenCount: String = "" dynamic var newsDate: String = "" dynamic var newsCategory: String = "" override static func primaryKey() -> String? { return "newsID" } } 

I'm trying to get

 let realm = try! Realm() let menuName = realm.objects(News) for i in menuName.filter("newsCategory") { nameLabel.text = i.newsCategory } 

But that does not work.

+6
source share
1 answer

Starting with Realm 3.10 you can now

Add Results.distinct (by:) / - [RLMResults distinctResultsUsingKeyPaths:], which return results containing only objects with unique values ​​in the specified key paths.

The old answer is before Kingdom 3.10

It is not yet possible to get "excellent" -like functionality from a Realm request (track the open problem here )

However, there are some workarounds suggested in the thread mentioned above (please read it to get the full context) by apocolipse user:

 // Query all users let allUsers = Realm().objects(User) // Map out the user types let allTypes = map(allUsers) { $0.type } // Fun part: start with empty array [], add in element to reduced array if its not already in, else add empty array let distinctTypes = reduce(allTypes, []) { $0 + (!contains($0, $1) ? [$1] : [] ) 

Or even better, another approach using Set (by jpsim user):

 let distinctTypes = Set(Realm().objects(User).valueForKey("type") as! [String]) 

Obviously, workarounds are not as effective as a direct database query, so use with caution (and test on a real load).

+7
source

Source: https://habr.com/ru/post/1011583/


All Articles