问题
I'm experimenting with CoreData in Swift 3 and have come up against a very bizarre circular compiler error in Xcode 8 beta.
NSFetchedResultsController needs a generic type parameter and AnyObject has worked fine up until now. The compiler throws the error:
Type 'AnyObject' does not conform to protocol 'NSFetchRequestObject'
To make me extra confused, if you delete the type parameter, XCode then says:
Reference to generic type NSFetchedResultsController requires argument in `<...>`
and helpfully suggests a fix using <AnyObject>
....and the cycle repeats.
This looks very much like a bug. Any ideas before I report it?
回答1:
If you take a look into NSFetchedResultsController
, you can clearly see that it has a parameter with name ResultType
which conforms to NSFetchRequestResult
. So you should pass a type
which conforms to NSFetchRequestResult
.
So if you take a look into NSFetchRequestResult
, you can see that it conforms to NSObjectProtocol
. Also NSDictionary
, NSManagedObject
and NSManagedObjectID
conforms to NSFetchRequestResult
.
public protocol NSFetchRequestResult : NSObjectProtocol {
}
extension NSDictionary : NSFetchRequestResult {
}
extension NSManagedObject : NSFetchRequestResult {
}
extension NSManagedObjectID : NSFetchRequestResult {
}
So it clear that you should pass a type
from any of these three NSDictionary
or NSManagedObject
or NSManagedObjectID
.
Create your instance of NSFetchedResultsController
like this.
let resultsController : NSFetchedResultsController<NSManagedObject>!
or like this
let resultsController : NSFetchedResultsController<NSManagedObjectID>!
or like this
let resultsController : NSFetchedResultsController<NSDictionary>!
回答2:
Any entity in your Core Data model maps as a subclass of NSManagedObject generated in your code so they all can be used to replace AnyObject, they all conform indirectly to NSFetchRequestResult protocol. You should see which entity/class is being fetch by your FetchRequest connected to this FetchedResultsController and that's the type you should use there.
来源:https://stackoverflow.com/questions/38158666/unable-to-instantiate-nsfetchedresultcontroller-with-generic-type-anyobject-in-s