我使用Realm数据库在
swift中做新闻应用程序.在我的数据库中有相同的新闻类别.如何从Realm数据库中获取独特的价值?
我用主键
我用主键
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" } }
我试着去
let realm = try! Realm() let menuName = realm.objects(News) for i in menuName.filter("newsCategory") { nameLabel.text = i.newsCategory }
但这不起作用.
从Realm 3.10开始,现在可以
Add Results.distinct(by:) / -[RLMResults
distinctResultsUsingKeyPaths:],which return a Results containing only
objects with unique values at the given key paths.
旧的回应 – 在Realm 3.10之前
现在还不可能从Realm查询中获得“独特”的功能(跟踪未解决的问题here)
但是,我在上面提到的主题中提出了一些解决方法(请通过用户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] : [] )
或者更好的是,使用Sets(通过用户jpsim)的不同方法:
let distinctTypes = Set(Realm().objects(User).valueForKey("type") as! [String])