Any的第一个语句不返回任何值,而第二个语句正常工作。是否可以将属性名称指定为避免硬编码的参数之一?
let predicate = NSPredicate(format: "%@ == %@", "id","553178666d61d70c24fe4221")
let predicate = NSPredicate(format: "id == %@", "553178666d61d70c24fe4221")
感谢@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;
}
答案 0 :(得分:3)
尝试使用%K
代替%@
作为属性名称。
像这样:
let predicate = NSPredicate(format: "%K == %@", "id","553178666d61d70c24fe4221")
来源:Predicates Syntax (developer.apple.com) 来自文档:
格式字符串支持printf样式的格式说明符,例如%x(请参阅格式化字符串对象)。两个重要的格式说明符是
%@
和%K
。
%@
是对象值的var arg替换 - 通常是字符串,数字或日期。
%K
是关键路径的var arg替换。