我有3个类似的表,我想存储在核心数据中。我想使用NSFetchedResultsController从公共视图控制器查看和编辑表。如何概括设置或使用子类来实现此目的?我的代码中的敌人示例如下所示
建议
是其中一个实体。我有另一个名为
的实体结果
我想使用(通过更改表中的单元格描述)并进行适当的其他更改。例如,我如何用变量表示Recommendation。
var moc:NSManagedObjectContext!
var fetchedResultsController: NSFetchedResultsController<Recommendation>!
var recommendations: [Recommendation] = []
和方法:
func setupFetchedResultsController() {
let dataRequest:NSFetchRequest<Recommendation> = Recommendation.fetchRequest()
let sortDescriptor = NSSortDescriptor(key:"recordNumber", ascending: true)
dataRequest.sortDescriptors = [sortDescriptor]
fetchedResultsController = NSFetchedResultsController(fetchRequest: dataRequest, managedObjectContext: moc, sectionNameKeyPath: #keyPath(Recommendation.recordNumber), cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch {
print(error.localizedDescription)
}
}
答案 0 :(得分:3)
您可以创建一个基本表视图控制器,其中包含要重写的属性。我建议像核心数据模板中建议的那样懒惰地初始化fetch控制器。
class BaseTableViewController: UITableViewController {
var managedObjectContext : NSManagedObjectContext!
// MARK: - Variables to be overridden
var entity : String { fatalError("entity must be overridden") }
var sortDescriptors : [NSSortDescriptor]? { return nil }
var cacheName : String? { return nil }
var sectionNameKeyPath : String? { return nil }
var fetchPredicate : NSPredicate? {
didSet {
fetchedResultsController.fetchRequest.predicate = fetchPredicate
}
}
...
lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: self.entity)
fetchRequest.predicate = self.fetchPredicate
fetchRequest.sortDescriptors = self.sortDescriptors
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: self.managedObjectContext!,
sectionNameKeyPath: self.sectionNameKeyPath,
cacheName: self.cacheName)
aFetchedResultsController.delegate = self
do {
try aFetchedResultsController.performFetch()
} catch let error as NSError {
self.present(error:error)
}
return aFetchedResultsController
}()
...
}
现在您可以继承控制器
class RecommendationViewController: BaseTableViewController {
// MARK: - Variables to overide
override var entity : String { return "Recommendation" }
override var sectionNameKeyPath : String? { return #keyPath(Recommendation.recordNumber) }
override var sortDescriptors : [NSSortDescriptor]? { return [NSSortDescriptor(key:"recordNumber", ascending: true)] }