加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在swift中从Realm数据库中获取唯一值

发布时间:2020-12-14 05:40:11 所属栏目:百科 来源:网络整理
导读:我使用Realm数据库在 swift中做新闻应用程序.在我的数据库中有相同的新闻类别.如何从Realm数据库中获取独特的价值? 我用主键 class News: Object { dynamic var newsID: String = "" dynamic var newsTitle: String = "" dynamic var newsFullText: String
我使用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])

显然,变通方法不如直接数据库查询有效,因此请谨慎使用(并在实际负载下进行测试).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读