[英]How to compare two values in Realm Swift
我有一个称为NewsCount
的Realm
数据库。 仅当有新新闻时(分别在newsCount
更改时),我才需要下载新新闻。 我与数据解析进行了比较。 但我无法正确比较它们。 您如何比较它们?
这是我的代码
private func parseJSONData(_ data: Data) {
do {
let temp: NSString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)!
let myNSData = temp.data(using: String.Encoding.utf8.rawValue)!
guard let jsonResult = try JSONSerialization.jsonObject(with: myNSData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary else {
return
}
guard let jsonNews = jsonResult["categories"] as? [AnyObject] else {
print("Empty array")
return
}
let realm = try Realm()
let category = realm.objects(NewsCount.self)
var array = [Int]()
for i in category {
array.append(i.newsCount)
}
print(array)
print("News COUNT2 \(category)")
for jsonnewes in jsonNews {
let newsJson = NewsCount()
//HERE I COMPARE
if !UserDefaults.standard.bool(forKey: "AppStarted") || jsonnewes["count"] as! Int > array[jsonnewes as! Int]{
newsJson.newsID = jsonnewes["term_id"] as! Int
newsJson.newsCount = jsonnewes["count"] as! Int
//print("News COUNT2 \(newsJson.newsCount)")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "downloadNew"), object: nil)
} else {
newsJson.newsID = jsonnewes["term_id"] as! Int
newsJson.newsCount = jsonnewes["count"] as! Int
//print("News COUNT3 \(newsJson.newsCount)")
}
insertOrUpdate(newsJson)
}
} catch {
print(error)
}
}
因为Realm使用RealmOptional来使用Int值,所以您必须调用归属于RealmOptional的值
尝试更改此:
for i in category {
array.append(i.newsCount.value)
}
首先,使用Int(string)
代替as! Int
可能更合适as! Int
as! Int
力投射到您的JSON数据转换为整数。
从外观jsonnewes
, jsonnewes
是一个充满JSON数据的字典,但是您将其强制转换为array[jsonnewes as! Int]
的数组索引array[jsonnewes as! Int]
array[jsonnewes as! Int]
(给定array
是数组而不是字典)不起作用。
相反,为了确保您明确检索到想要的项目,我建议使用Realm的主键查询方法来检索想要的项目。
let realm = try! Realm()
for newsItem in jsonNews {
let newsPrimaryKey = Int(newsItem)
let realmNews = realm.object(ofType: NewsCount.self, forPrimaryKey: newsPrimaryKey)
// Don't continue if a Realm object couldn't be found
guard let realmNews = realmNews else {
continue
}
// Perform comparison
if Int(newsItem["count"]) > realmNews.newsCount {
// Perform the update
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.