iosswiftcore-dataswift4.2

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


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

Solution

  • 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