Applying Query in core data

A

There are few cases when we prefer to use Core data that Sqlite. Core data is faster in fetching records than SQLite. As like sqlite we can fetch data by specifying query in Core data.

Following is the way to set your query for fetch request of core data.

let request = NSFetchRequest()
if #available(iOS 10.0, *)
{
request.entity = EmpData.entity()
}
else
{
request.entity = NSEntityDescription.entity(forEntityName: “EmpData”, in: context)
}

let name = “Ram”

request.predicate = NSPredicate(format: “empName == %@”,empName)

do{
let results = try context.fetch(request)

….
….
….
….

}
catch
{

}

Also Some times we required to fetch only few number of records each time. For example you have large amount of data then we need to fetch data in batches.

Following is the code to do this

request.fetchLimit = 100
request.fetchOffset = recordCount

where fetchLimit is amount of records you want each time to fetch and fetchOffset is from where to start. Here recordCount is the counter to keep track from where to start the fetch for next time.

About the author

trupti.karale
By trupti.karale

Category