Jamil
Jamil

Reputation: 940

swift CoreData predicates

I'm adding CoreData to my app. Simple fetching is ok, but when i try to fetch data with predicate i get exception in AppDelegate.

func fetchWithPredicate(table: String, pred: String)->NSArray
{
    var appDel : AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate);
    var context : NSManagedObjectContext = appDel.managedObjectContext
    var request = NSFetchRequest(entityName: table)
    request.predicate = NSPredicate(format: pred)//exception occurs on this string
    request.returnsObjectsAsFaults = false
    var results: NSArray = NSArray()
    do{
        results = try context.executeFetchRequest(request)
    }

    catch{}

    return results
}

My predicate looks like this: "routeFormed == %@"+route.identifier! , where route.identifier is String. Should i add something to AppDelegate or to my entities? Also, i opened .sqlite file with sqlitebrowser, should i add predicates using visible names or the ones that i see in database(i.e. "routeFormed" or "ZROUTEFORMED")?

Upvotes: 3

Views: 2923

Answers (1)

Martin R
Martin R

Reputation: 540005

Do not create predicates as strings, that is bound to fail in any but trivial cases. Create the predicate as

let predicate = NSPredicate(format: "routeFormed == %@", route.identifier)

or

let predicate = NSPredicate(format: "%K == %@", "routeFormed", route.identifier)

and pass that to the fetch request. The keys in the predicate are the names of the entity properties as defined in the Core Data model inspector.

Upvotes: 4

Related Questions