0

I have a DB with fields like below

Latitude Longitude Flag 54.1425 98.2564 0 52.1036 94.1458 3 51.1569 92.1458 3 50.1326 91.1458 3 56.1236 93.1458 0

I need to retrieve records that have flag as 3.

    let fetchRequest = NSFetchRequest()

    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    let entityDescription = NSEntityDescription.entityForName("TABLE_LOCATION", inManagedObjectContext: managedContext)




    // Configure Fetch Request
    fetchRequest.entity = entityDescription


    do {
        let result = try managedContext.executeFetchRequest(fetchRequest)
        //print(result)


    } catch {
        let fetchError = error as NSError
        print(fetchError)
    }

All i have is the above code that retrieves all records from the table TABLE_LOCATION any code or working example is much appreciated

Thanks!

Carey
  • 139
  • 2
  • 9

3 Answers3

4

You need to add a NSPredicate to your fetchRequest.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/

fetchRequest.predicate = NSPredicate(format: "flag == %@", "3")
Ahmed Onawale
  • 3,992
  • 1
  • 17
  • 21
0

You can use a NSPredicate and set it to the fetchRequest. Create a NSPredicate and set it to the fetchRequest before you execute the fetch request.

fetchRequest.predicate = NSPredicate(format: "flag = 3")
nhgrif
  • 61,578
  • 25
  • 134
  • 173
Pradeep K
  • 3,671
  • 1
  • 11
  • 15
0

Change Your function to:

func fetchDistinctDataUsingReq(predicate :NSPredicate) -> NSArray {
   let fetchRequest = NSFetchRequest()
   fetchRequest.predicate = predicate
   //Rest of your code
}

Now call this function from using:

let predicate = NSPredicate(format: "flag == %@", 3)
self.fetchDistinctDataUsingReq(predicate)

This is a much better approach and can be reused across fetching. Additionally you can pass the CoreData Table as parameter along with predicate to generalize it.

Arun Gupta
  • 2,628
  • 1
  • 20
  • 37