如何通过在核心数据中搜索来获取行的特定数据作为字典

How to get specfic data of row as dictionary by search in coredata

我已经在核心数据中添加了通过 product_id 进行搜索的代码,但是 returns 我只想从包含 product_id[=11= 的行中获取特定数据的所有记录]

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "CartEntity")
        let predicate = NSPredicate(format: "product_id == %@", "\(Product_id)")
        request.predicate = predicate
        request.fetchLimit = 1

        do{
            let count = try managedContext.count(for: request)
            if(count == 0){
            // no matching object
                print("no")
                self.savecoredata()
            }
            else{
                let request = NSFetchRequest<NSFetchRequestResult>(entityName: "CartEntity")
                       request.returnsObjectsAsFaults = false
                       do {
                           let result = try managedContext.fetch(request)
                           for dataresult in result as! [NSManagedObject] {
                               let userName = dataresult.value(forKey: "proname") as! String
                               let age = dataresult.value(forKey: "price") as! String
                               print("User Name is : "+userName+" and price is : "+age)
                            print(datastored)
                           }
                       } catch {
                           print("Fetching data Failed")
                       }
                print("yes")
//                deleteFeed(id: "\(Product_id)")
                // first delete old and than insert new id
            }
          }
        catch let error as NSError {
             print("Could not fetch \(error), \(error.userInfo)")
          }

问题是您必须满足不同的请求,首先您使用一个 带有 谓词,然后您使用一个不带谓词的请求,它将 return 所有行。也可以为第二个请求重用谓词,或者更好地跳过第一个似乎不必要的 count 请求并仅执行第二个

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "CartEntity")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "product_id == %@", "\(Product_id)")
do {
    let result = try managedContext.fetch(request)
    for dataresult in result as! [NSManagedObject] {
//... rest of code

首先使用第一个请求的谓词,然后使用特定的提取请求 return 实际的 NSManagedObject 子类。好处是直接使用点符号而不是使用容易出错的 KVC(键值编码)来获取值。

这是你整个代码的对应逻辑,但是savecoredata行似乎没有意义

let request : NSFetchRequest<CartEntity> = CartEntity.fetchRequest()
request.predicate = NSPredicate(format: "product_id == %ld", Product_id)

do {
   if let result = try managedContext.fetch(request).first {
       let userName = result.proname
       let price = result.price
       print("User Name is : \(userName) and price is : \(price)")
   } else {
       // no matching object
       print("no")
       self.savecoredata()
   }
} catch {
   print(error)
}

问题似乎与您的谓词有关。检查 product_id 是字符串还是整数。如果您正在进行转换,请应用格式 "%d", "%ld"

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "CartEntity")
let predicate = NSPredicate(format: "product_id = \(Product_id)")
request.predicate = predicate
request.fetchLimit = 1
var count = 0
do{
    count = try managedContext.count(for: request)
}
catch let error {
    print("Could not fetch \(error), \(error.localizedDescription)")
}

guard count != 0 else {
    // no matching object
    print("no")
    self.savecoredata()
    return
}

// remove predicate, which is actually not required.
request.predicate = nil

request.returnsObjectsAsFaults = false
do {
    let result = try managedContext.fetch(request)
    for dataresult in result as! [NSManagedObject] {
        let userName = dataresult.value(forKey: "proname") as! String
        let age = dataresult.value(forKey: "price") as! String
        print("User Name is : "+userName+" and price is : "+age)
        print(datastored)
    }
} catch let error {
    print("Fetching data Failed - \(error)")
}
print("yes")
// deleteFeed(id: "\(Product_id)")
// first delete old and than insert new id