prepareForSegue与自定义Swift NSManagedObject:自定义类崩溃?

时间:2015-01-20 19:31:08

标签: ios swift core-data crash segue

fetchedresultController不会在prepareForSegue中返回我的自定义nsmanagedObject。

当我在tableView中添加一个新条目(“+”按钮调用“insertNewObject”)时,会出现一个正确的文本来自我的自定义对象的名称。但是当我单击该行来执行segue时,会出现崩溃,断点,我点击继续,程序会继续,而不会添加更多信息。

将nsmanagedObject强制转换为Section类的代码:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            println("idx: \(indexPath) , objet : \(self.fetchedResultsController.objectAtIndexPath(indexPath))") //outputs ""
        let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as Section//NSManagedObject
            let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController

            //controller.detailItem = object
            controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}





var fetchedResultsController: NSFetchedResultsController {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }
    let fetchRequest = NSFetchRequest()
    let entity = NSEntityDescription.entityForName("Section", inManagedObjectContext: self.managedObjectContext!)
    fetchRequest.entity = entity
    fetchRequest.fetchBatchSize = 20
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: false)
    let sortDescriptors = [sortDescriptor]
    fetchRequest.sortDescriptors = [sortDescriptor]
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    var error: NSError? = nil
    if !_fetchedResultsController!.performFetch(&error) {
         abort()
    }
    return _fetchedResultsController!
}    
var _fetchedResultsController: NSFetchedResultsController? = nil




func insertNewObject(sender: AnyObject) { //this works
    let context = self.fetchedResultsController.managedObjectContext
    let entity = self.fetchedResultsController.fetchRequest.entity!

    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as Section

    newManagedObject.name = String("insert")        
    var error: NSError? = nil
    if !context.save(&error) {
        abort()
    }
}


func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
    let section = self.fetchedResultsController.objectAtIndexPath(indexPath) as Section
    cell.textLabel.text = section.name;//this works
}

0 个答案:

没有答案