在下面的代码中,我可以使用Core Data存储数据。我存储的数据是奖励。如何从核心数据中获取奖励数据?每当有特定用户添加了奖励时,我如何从我的核心数据中获得总奖励?我为每个用户使用loggedInUserHouseNumber。如何获取与loggedInUserHouseNumber相等的奖励数据和奖励总数? 。我想获取所有数据和总奖励等于登录的用户房号,任何人都可以提供答案吗?

 loggedInUserHouseNumber =  (UserDefaults.standard.value(forKey: "loggedInUserHouseNumber")  as! String)

获取请求代码
let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "GroceryItem")
        request.returnsObjectsAsFaults = false


self.saveReward(reward: rewardInt)

保存数据代码:
func saveReward(reward: Int64){
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let groceryData = GroceryItem(context: context) // Link GroceryItem & Context
    groceryData.reward = reward
    groceryData.isSelected = false
    groceryData.houseNo = loggedInUserHouseNumber
    //        print("data:", groceryItem.name)
    print("ang reward nga na save: ", groceryData.reward)
    print("jelordrey")
    (UIApplication.shared.delegate as! AppDelegate).saveContext()
}

最佳答案

您需要使用 NSPredicate 来查询特定的房屋编号,您可以尝试以下示例代码。

let loggedInUserHouseNumber =  (UserDefaults.standard.value(forKey: "loggedInUserHouseNumber")  as! String)
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "GroceryItem")
//Create query
request.predicate = NSPredicate(format: "houseNo = %@", loggedInUserHouseNumber ?? "")
 do {

       if let models = try context.fetch(request) as? [GroceryItem] {
        // You will get count
        let count = models.count
        var total = 0
         for model in models {
            total = total + model. reward
       }

    }
   } catch let error {
        // Handle error
    }

关于ios - 使用核心数据获取存储的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49713910/

10-09 16:16
查看更多