我有一个UIViewController
子类MyViewController
,其中包含NSFetchedResultsController
和NSManagedObjectContext
。但是,当我去创建NSFetchedResultsController
时,它表示MyViewController
上没有托管对象属性。
var managedObjectContext: NSManagedObjectContext!
var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Post", inManagedObjectContext: self.managedObjectContext)
fetchRequest.entity = entity
fetchRequest.fetchBatchSize = 50
}()
我不清楚在它之前声明了一个managedObjectContext变量吗?我做错了什么?
答案 0 :(得分:1)
属性的初始化程序无法引用同一属性 class 除非将其声明为 lazy 计算属性。
您也忘了从闭包中返回一个获取的结果控制器。
var managedObjectContext: NSManagedObjectContext!
lazy var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Post", inManagedObjectContext: self.managedObjectContext)
fetchRequest.entity = entity
fetchRequest.fetchBatchSize = 50
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}()