Unable to instantiate NSFetchedResultController wi

2019-06-24 11:57发布

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'

Screen shot

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?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-24 12:17

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>!
查看更多
叛逆
3楼-- · 2019-06-24 12:19

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.

查看更多
登录 后发表回答