JoakimE
JoakimE

Reputation: 1874

Do this to core data: "Select * WHERE "attribute" == "Some string" "

I did manage to do this by making a function with a loop that checks the attribute to a string. But i'm looking for a better way to do this.

In sql I do this:

Select * WHERE "attribute" == "string"

Is there a method to do this in swift?

My function looks like this:

func tableData()
{
    let objects = retrieveValues("JobTime") //Retrieve a NSMutableArray
    if !objects.isEmpty
    {
        for var index = 0; index < objects.count; ++index
        {
            if objects[index].valueForKey("jobTitle") as? String == transferTitle
            {
                print("Job title matched: \(index)")
            }
            else
            {
                print("Nothing here!")
            }
        }
      }
   }

Upvotes: 5

Views: 6931

Answers (2)

Rafał Augustyniak
Rafał Augustyniak

Reputation: 2031

In order to perform fetch request in CoreData you have to initialise NSFetchRequest class. In order to specify in what kind of entities you are interested you create NSPredicate class. It gives you ability to specify pretty advanced queries. In most cases the simplest way to create NSPredicate is by using format string - details about the syntax can be found Apple's Predicate Format String Syntax document.

You can find example of how you can perform fetch request in CoreData (and Swift) below.

let managedObjectContext: NSManagedObjectContext
let predicate = NSPredicate(format: "jobTitle == %@", "Programmer")

let fetchRequest = NSFetchRequest.init(entityName: "People")
fetchRequest.predicate = predicate
//fetchRequest.sortDescriptors = [] //optionally you can specify the order in which entities should ordered after fetch finishes

let results = managedObjectContext.executeFetchRequest(fetchRequest)

Upvotes: 12

MirekE
MirekE

Reputation: 11555

You can pass the query to CoreData and only retrieve what you want. The NSManagedObjectContext class has a executeFetchRequest method that you call to retrieve data from the database. You pass NSFetchRequest object to it. That object contains a NSPredicate, which defines your query.

Upvotes: 1

Related Questions