Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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!")
            }
        }
      }
   }
like image 947
JoakimE Avatar asked Dec 18 '22 20:12

JoakimE


1 Answers

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)
like image 133
Rafał Augustyniak Avatar answered Dec 24 '22 01:12

Rafał Augustyniak