Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique value from Realm database in swift

I do news application in swift using Realm database. In my database have same news categories. How to get unique value from Realm database? I use 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 try to get

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

But it is not work.

like image 510
Zhanserik Avatar asked Oct 22 '16 10:10

Zhanserik


1 Answers

Starting from Realm 3.10 it's now possible to

Add Results.distinct(by:) / -[RLMResults distinctResultsUsingKeyPaths:], which return a Results containing only objects with unique values at the given key paths.

Old response - before Realm 3.10

It is not possible yet to obtain a "distinct"-like functonality from a Realm query (track the open issue here)

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

// 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 better yet, a different approach using Sets (by user jpsim):

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

Obviously the workarounds aren't as efficient as a direct DB query, so use with care (and testing under realistic load).

like image 96
Bogdan Farca Avatar answered Nov 16 '22 04:11

Bogdan Farca