Reputation: 2710
AnyThe first statement doesn't return any values, while second one works correctly. Is it possible to specify property name as one of the arguments to avoid hard coding?
let predicate = NSPredicate(format: "%@ == %@", "id","553178666d61d70c24fe4221")
let predicate = NSPredicate(format: "id == %@", "553178666d61d70c24fe4221")
That's a complete solution thanks to @FreeNickname
class func searchForObject(propertyName:NSString,property:NSString,className:String,single:Bool )->AnyObject?{
let fetchRequest = NSFetchRequest(entityName: className)
let predicate = NSPredicate(format: "%K == %@", argumentArray: [propertyName, property])
var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
fetchRequest.predicate = predicate
// Execute the fetch request, and cast the results to an array of LogItem objects
var error:NSError?
if let fetchResults = appDelegate.managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as [AnyObject]? {
if let e = error{
println(e.debugDescription)
}
if single {
var object: AnyObject? = fetchResults.first
return object;
}
else{
return fetchResults
}
}
return nil;
}
Upvotes: 1
Views: 442
Reputation: 7764
Try %K
instead of %@
for the attribute name.
Like so:
let predicate = NSPredicate(format: "%K == %@", "id","553178666d61d70c24fe4221")
Source: Predicates Syntax (developer.apple.com) From the docs:
The format string supports printf-style format specifiers such as %x (see Formatting String Objects). Two important format specifiers are
%@
and%K
.
%@
is a var arg substitution for an object value—often a string, number, or date.
%K
is a var arg substitution for a key path.
Upvotes: 3