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

466 Views Asked by At

i had added this code for search via product_id in coredata but that returns all records i want to just get specific data from row that contain that product_id

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

There are 3 best solutions below

1
Joakim Danielson On BEST ANSWER

The problem is that you have to different requests, first you use one with a predicate and then you use one without a predicate which will return all rows. Either reuse the predicate for the second request as well or even better skip the first count request that seems unnecessary and perform only the second one

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
0
vadian On

First of all use the predicate of the first request and secondly use a specific fetch request to return the actual NSManagedObject subclass. The benefit is to get the values directly with dot notation rather than with error-prone KVC (key-value coding).

This is the corresponding logic of your entire code, however the savecoredata line seems to be pointless

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)
}
0
Ankit Thakur On

The issue seems to be with your predicate. Check if the product_id is string or integer. If you are doing casting then apply format "%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