我正在研究Udacity上的CoreData项目,并且很难实现fetchedResultsController。我尝试使用lazy var实例化fetchedResultsController,但它提示我"实例成员上下文不能用于类型' ViewController'。我的代码是这样的:
//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)
}()
这样做会在&#39;上下文中给出错误信息。在fetchedResultsController中指示:
实例成员&#39; context&#39;不能在类型&#39; ViewController&#39;
上使用
我有什么不对的吗?非常感谢任何建议,谢谢!
答案 0 :(得分:2)
在lazy属性中引用self
时,您需要明确使用context
:
return NSFetchedResultsController(fetchRequest: fetchedRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)