Jamil Jamil - 1 year ago 192
iOS Question

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


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()
results = try context.executeFetchRequest(request)


return results

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

Answer Source

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)


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download