NSFetchedResultsController - 在展开Optional值时意外发现nil

时间:2015-10-09 15:09:54

标签: ios swift nsfetchedresultscontroller nsfetchrequest

我使用NSFetchedResultsController来填充我的TableView。我有一个实体“HubProfile”,其属性为:“Name”& “HubID”

问题: NSFetchedResultsController即将来临nil。奇怪的是,当我在fetchedResultsController&中打印viewDidLoadcellForRowIndexPath方法 - 它给出了一个值。但在numberOfRowsInSection方法中,fetchedResultsControllernil且应用崩溃。

此外,数据已保存在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
}}

1 个答案:

答案 0 :(得分:0)

tableView可能在fetchResultsController有机会加载之前已经加载。因此,在您执行performFetch()之后立即重新加载表:

  do
{
    try! fetchedResultsController.performFetch()
    tableView.reloadData()
}

print(fetchedResultsController)  //THIS IS NOT NIL
}

然后在tableView函数中检查fetchedResultsController是否为nil,如果给它其他一些值(在本示例中为0),并且在获取完成后重新加载表时,该函数将从您的项目中获取项目fetchResultsController(当它为!= nil时):

    override func numberOfSections(in tableView: UITableView) -> Int {
           return fetchedResultsController.sections?.count ?? 0
    }