Search code examples
swiftcore-dataswift2nsfetchrequestexecutefetchrequest

How to retrieve CoreData that satisfies a condition swift 2


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!


Solution

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