NSFetchedResultsController-展开一个可选值时意外发现nil

问题描述 投票:0回答:1

我正在使用NSFetchedResultsController填充我的TableView。我有一个实体“ HubProfile”,其属性为:“名称”和“ HubID”

问题: NSFetchedResultsController即将到来nil。奇怪的是,当我以fetchedResultsControllerviewDidLoad方法打印cellForRowIndexPath时,它会给出一个值。但是在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
}}
ios swift nsfetchedresultscontroller nsfetchrequest
1个回答
0
投票

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 } }

© www.soinside.com 2019 - 2024. All rights reserved.