核心数据的托管对象 属性 作为参数
Core data's managed object property as argument
Any 第一个语句没有 return 任何值,而第二个语句工作正常。是否可以将 属性 名称指定为参数之一以避免硬编码?
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;
}
尝试使用 %K
而不是 %@
作为属性名称。
像这样:
let predicate = NSPredicate(format: "%K == %@", "id","553178666d61d70c24fe4221")
来源:Predicates Syntax (developer.apple.com)
来自文档:
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.
Any 第一个语句没有 return 任何值,而第二个语句工作正常。是否可以将 属性 名称指定为参数之一以避免硬编码?
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;
}
尝试使用 %K
而不是 %@
作为属性名称。
像这样:
let predicate = NSPredicate(format: "%K == %@", "id","553178666d61d70c24fe4221")
来源:Predicates Syntax (developer.apple.com) 来自文档:
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.