2017-04-25 109 views
7

我在學習如何使用Realm Swift和Charts,這樣我最終可以在我正在構建的應用程序中使用它們,並且我正在搞定一段時間領域。最終,我計劃讓Charts查看我的Realm DB,然後根據數據顯示圖表,但在此之前,我需要檢查是否存在領域對象(如果不存在),以創建然後當用戶使用該應用程序時,將「計數」添加到該記錄並相應地更新圖表。如何更新realm中的對象swift

正如我正在學習,我已經把它分解成幾個步驟。我已經想通了如何檢查,看是否有記錄存在,如果不這樣構建它:

我的境界型號:

class WorkoutsCount: Object{  
    dynamic var date: Date = Date() 
    dynamic var count: Int = Int(0) 
} 

// function to check if this weeks days have been created in Realm DB yet and creates them if not 
    let realm = try! Realm() 
    lazy var workouts: Results<WorkoutsCount> = { self.realm.objects(WorkoutsCount.self)}() 
    let startOfWeekDate = Date().startOfWeek(weekday: 1) 
    let nextDay = 24 * 60 * 60 

    // checks the DB to see if it contains the start of this week 
    func searchForDB(findDate: Date) -> WorkoutsCount?{ 
     let predicate = NSPredicate(format: "date = %@", findDate as CVarArg) 
     let dateObject = self.realm.objects(WorkoutsCount.self).filter(predicate).first 

     if dateObject?.date == findDate{ 
      return dateObject 
     } 
     return nil 
    } 

    func setThisWeeksDays(){ 
     //if the beginning of this week doesn't exist in the DB then create each day with 0's as the count data 
     if searchForDB(findDate: startOfWeekDate) == nil{ 
      try! realm.write() { 

       let defaultWorkoutDates = [startOfWeekDate, startOfWeekDate + TimeInterval(nextDay), startOfWeekDate + TimeInterval(nextDay*2), startOfWeekDate + TimeInterval(nextDay*3), startOfWeekDate + TimeInterval(nextDay*4), startOfWeekDate + TimeInterval(nextDay*5), startOfWeekDate + TimeInterval(nextDay*6)] 

       for workouts in defaultWorkoutDates { 
        let newWorkoutDate = WorkoutsCount() 
        newWorkoutDate.date = workouts 
        self.realm.add(newWorkoutDate) 
       } 
      }    
      workouts = realm.objects(WorkoutsCount.self) 
     } 
    } 

我已驗證通過瀏覽器領域他的作品應用程序。

我的待辦事項列表的下一步是找出如何更新「今日日期記錄」的記錄。要做到這一點,我創建了一個按鈕,所以當點擊它會試圖做到這一點。我一直在谷歌搜索和谷歌搜索,並開始思考,因爲我沒有在我的模型中使用主鍵,我必須先刪除有問題的特定記錄,然後再添加新的數據。我不能爲我的生活弄清楚如何根據Realm文檔和更多的Google搜索來做到這一點。這是我已經有了,但它不工作:

@IBAction func btnUpdate1MW(_ sender: Any) { 
     if searchForDB(findDate: today) != nil{ 
      if plusOne <= 7{ 
       plusOne += 1 
       CounterImage1MW.image = UIImage(named: "1MWs-done-\(plusOne)") 

       let realm:Realm = try! Realm() 

       // deletes the original item prior to being updated and added back below 
       let removeTodaysItem = today 
       let workout = realm.objects(WorkoutsCount.self).filter("date = '\(removeTodaysItem)'") 
       if workout.count > 0{ 
        for date in workout{ 
         try! realm.write { 
          realm.delete(date) 
         } 
        } 
       } 
       // adds back the item with an updated count 
       do { 
        let realm = try Realm() 
        try realm.write { 
         realm.create(WorkoutsCount.self, value: ["date": today, "count": plusOne], update: false) 
        } 
       } catch let error as NSError { 
        fatalError(error.localizedDescription) 
       } 
      } 

      print("add to 1MW + 1") 
     } 
    } 

當我點擊了btnUpdate1MW按鈕,我碰到下面的錯誤在Xcode:

終止應用程序由於未捕獲的異常「值無效',原因:類型爲'WorkoutsCount'的對象的類型日期屬性'date'的預期對象,但收到:2017-04-24 07:00:00 +0000'

+0

爲什麼你不使用主鍵?當您想要更新現有對象時,它就是爲這些場景設計的。使用它比刪除和重新創建對象更方便,同時它也是一個更優化的解決方案。 –

+0

因爲當返回並添加一個主鍵時,它打破了我已經有的工作,在第一組代碼中的「let realm = try!Realm()」行出錯,我無法弄清楚解決這個問題。由於我花了一天時間才完成這項工作,感覺我正在退步。 – jammyman34

+0

您是否向您的AppDelegate applicationDidFinishLaunching方法添加了遷移塊? 如果不是這樣,那就是您出現錯誤的原因,每次更改Realm模型時都會得到相同的錯誤。 –

回答

20

更新對象只是分配寫入事務中的屬性的值。看我們的文檔。

https://realm.io/docs/swift/latest/#updating-objects

所以您不必刪除,然後添加一個對象。只需在寫入事務中爲屬性賦予新的值,如下所示。

let workouts = realm.objects(WorkoutsCount.self).filter("date = %@", removeTodaysItem) 

let realm = try! Realm() 
if let workout = workouts.first { 
    try! realm.write { 
     workout.date = today 
     workout.count = plusOne 
    } 
} 

供參考:請不要在查詢中使用字符串插值。通常通過字符串插值構造一個重要的字符串是不好的做法使用NSPredicate的字符串替代語法,如filter("date = %@", removeTodaysItem)

+0

是否有一種方法來設置'workouts'var,以便使用CONTAIN進行過濾因爲我一直在嘗試使用Predicates並且文檔不明確,所以我無法弄清楚該語法,因此我不能弄清楚要麼...我意識到'不要使用字符串插值'這一點,但我絕望,這些都是我在網上找到的例子,但謝謝澄清:) – jammyman34