我正在使用NSFetchedResultsController
填充我的TableView。我有一个实体“ HubProfile”,其属性为:“名称”和“ HubID”
问题: NSFetchedResultsController
即将到来nil
。奇怪的是,当我以fetchedResultsController
和viewDidLoad
方法打印cellForRowIndexPath
时,它会给出一个值。但是在numberOfRowsInSection
方法中,fetchedResultsController
为nil
,应用程序崩溃。
而且数据已经保存在CoreData中。我已经在SQLite浏览器中看到它-因此有要加载的数据
似乎无法弄清楚原因。
下面是我的代码:
class StudentsController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate
{
let managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
//FETCH REQUESTS
let fetchRequest = NSFetchRequest(entityName: "HubProfile")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate = NSPredicate(format: "hubID = %@", hubID!)
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
do
{
try! fetchedResultsController.performFetch()
}
print(fetchedResultsController) //THIS IS NOT NIL
}
//TABLEVIEWDATASOURCE PROTOCOL:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(fetchedResultsController) // THIS IS NIL
let sectionInfo = fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! StudentsCell!
print(fetchedResultsController) //THIS is NOT Nil
let hubProfile = fetchedResultsController.objectAtIndexPath(indexPath) as! HubProfile
cell.nameLabel?.text = hubProfile.name
return cell
}}
tableView可能在fetchResultsController有机会加载之前已经加载。因此,在您执行performFetch()之后立即重新加载表:
do
{
try! fetchedResultsController.performFetch()
tableView.reloadData()
}
print(fetchedResultsController) //THIS IS NOT NIL
}
<< ):override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if fetchedResultsController != nil {
return fetchedResultsController.sections![section].numberOfObjects
} else {
return 0 //or whatever other default value you want
}
}