如何将类型应用于 NSFetchRequest 实例? [英] How to apply the type to a NSFetchRequest instance?
问题描述
在 Swift 2 中,以下代码有效:
In Swift 2 the following code was working:
let request = NSFetchRequest(entityName: String)
但是在 Swift 3 中它给出了错误:
but in Swift 3 it gives error:
无法推断通用参数ResultType"
Generic parameter "ResultType" could not be inferred
因为 NSFetchRequest
现在是一个泛型类型.他们在文档中这样写道:
because NSFetchRequest
is now a generic type. In their documents they wrote this:
let request: NSFetchRequest<Animal> = Animal.fetchRequest
所以如果我的结果类是例如 Level
我应该如何正确请求?
so if my result class is for example Level
how should I request correctly?
因为这不起作用:
let request: NSFetchRequest<Level> = Level.fetchRequest
推荐答案
let request: NSFetchRequest<NSFetchRequestResult> = Level.fetchRequest()
或
let request: NSFetchRequest<Level> = Level.fetchRequest()
取决于您想要的版本.
你必须指定泛型类型,否则方法调用是不明确的.
You have to specify the generic type because otherwise the method call is ambiguous.
第一个版本是为 NSManagedObject
定义的,第二个版本是为每个使用扩展名的对象自动生成的,例如:
The first version is defined for NSManagedObject
, the second version is generated automatically for every object using an extension, e.g:
extension Level {
@nonobjc class func fetchRequest() -> NSFetchRequest<Level> {
return NSFetchRequest<Level>(entityName: "Level");
}
@NSManaged var timeStamp: NSDate?
}
重点是去除字符串常量的使用.
The whole point is to remove the usage of String constants.
这篇关于如何将类型应用于 NSFetchRequest 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!