2017-01-23 28 views
0

我有一個名爲NewsCountRealm數據庫。只有在有新消息時(分別在newsCount更改時),我才需要下載新消息。我和數據解析進行比較。但我無法正確比較它們。你如何比較它們?如何比較Realm Swift中的兩個值

myImage

氏是我的代碼

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) 
} 
} 

回答

0

因爲領域使用RealmOptional使用int類型,你必須在值屬性附加傷害打電話到RealmOptional

嘗試改變這一點:

for i in category { 
     array.append(i.newsCount.value) 
    } 
0

首先,它可能更適合我們e Int(string)而不是as! Int強制轉換將您的JSON數據轉換爲整數。

從外觀上來看,jsonnewes是一本字典充滿JSON數據,但你鑄造它作爲在array[jsonnewes as! Int]數組索引(給出array是一個數組,而不是一個字典)不應該工作。

相反,爲了確保您明確檢索您想要的物品,我建議您使用Realm's primary key query method以檢索您想要的物品。

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 
    } 
}