2017-08-15 34 views
0

我有一個應用程序,每次使用swipe刪除tableviewcell函數時,都會將數量5添加到我的核心數據屬性值中。核心數據結構是這樣的:https://i.stack.imgur.com/16YR6.png在提交editingStyle類的代碼如下所示:當UITableView爲空時無法獲取CoreData屬性值

if editingStyle == UITableViewCellEditingStyle.delete{ 

     let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest() 
     do { 
      let array_users = try context.fetch(fetchRequest) 

      let user = array_users[0] 
      var count: Int64 = user.value(forKey: "totalGold") as! Int64 
      count += 5 
      user.setValue(count, forKey: "totalGold") 
      let str = String(describing: user.value(forKey: "totalGold") as! Int64) 
      totalGold.text = str 
      do { 
       try context.save() 
       print("saved!") 
      } catch let error as NSError { 
       print("Could not save \(error), \(error.userInfo)") 
      } catch { 

      } 

      } 

      catch { 
      print("Error with request: \(error)") 
      } 
let managedObject: NSManagedObject = controller.object(at: indexPath) as NSManagedObject; 
     context.delete(managedObject) 
     ad.saveContext() 
    } 
} 

然後我用同樣的抓取過程中viewDidLoad中,像這樣:

let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest() 
    do { 

     let array_users = try context.fetch(fetchRequest) 

     let user = array_users[0] 
     let count: Int64 = user.value(forKey: "totalGold") as! Int64 
     user.setValue(count, forKey: "totalGold") 
     let str = String(describing: user.value(forKey: "totalGold") as! Int64) 
     totalGold.text = str 




     //save the context 
     do { 
      try context.save() 
      print("saved!") 
     } catch let error as NSError { 
      print("Could not save \(error), \(error.userInfo)") 
     } catch { 

     } 

     } catch { 
     print("Error with request: \(error)") 
    } 

此代碼工作正常除非表格視圖中沒有表格視圖單元格。然後,當我嘗試雖然沒有細胞重新加載的觀點,我得到一個索引超出範圍的錯誤,而試圖在行提取:

let user = array_users[0] 

顯然,這是由於這樣的事實,當我嘗試爲totalGold獲取最新值,它找不到它,它認爲沒有任何值,所以我在提取錯誤。如何正確獲取totalGold的最新屬性值?

回答

0

你可以把那些在條件

let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest() 
    do { 
     let array_users = try context.fetch(fetchRequest) 
     if array_users.count > 0 { 
      let user = array_users[0] 
      let count: Int64 = user.value(forKey: "totalGold") as! Int64 
      user.setValue(count, forKey: "totalGold") 
      let str = String(describing: user.value(forKey: "totalGold") as! Int64) 
      totalGold.text = str 

      //save the context 
      do { 
       try context.save() 
       print("saved!") 
      } catch let error as NSError { 
       print("Could not save \(error), \(error.userInfo)") 
      } catch { 
      } 
     } 
    } catch { 
     print("Error with request: \(error)") 
    } 
+0

出於某種原因,這並沒有解決問題。現在,當視圖加載時,totalGold屬性值將被重置,並且文本標籤會像默認值一樣讀取「0」。 –