Reputation: 2897
I am working on the CoreData project on Udacity and am having difficulty implementing fetchedResultsController. I attempted to instantiate fetchedResultsController with a lazy var but it prompts me "Instance member context cannot be used on type 'ViewController'. My codes as such:
//AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let stack = CoreDataStack(modelName: "Model")
...
}
//ViewController
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, MKMapViewDelegate{
lazy var context: NSManagedObjectContext = {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.stack!.context
}()
lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
let fetchedRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
fetchedRequest.sortDescriptors = []
return NSFetchedResultsController(fetchRequest: fetchedRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
}()
Doing so will give me an error line at the 'context' in fetchedResultsController indicating:
Instance member 'context' cannot be used on type 'ViewController'
Is there anything I'm doing wrong? Any advice is much appreciated, thanks!
Upvotes: 1
Views: 846
Reputation: 10199
You need to explicitly use self
when referring to context
in the lazy property:
return NSFetchedResultsController(fetchRequest: fetchedRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
Upvotes: 2