Uitableview fetchedResultsController核心数据致命错误:在展开可选值时意外发现nil

Uitableview fetchedResultsController核心数据致命错误:在展开可选值时意外发现nil,uitableview,swift,core-data,null,optional-values,Uitableview,Swift,Core Data,Null,Optional Values,我知道有无数的问题都有同样的错误,但没有一个解决方案是有效的 我想制作一个博客阅读器应用程序,从CoreData中保存和获取数据。我可以将JSON结果保存到CoreData中,但是当我试图检索它以在tableView中显示时,它会崩溃,出现致命错误:在第行展开可选值时意外发现nil let entity=NSEntityDescription.entityForName(“Blog”,inManagedObjectContext:self.managedObjectContext!) 这是我的密

我知道有无数的问题都有同样的错误,但没有一个解决方案是有效的

我想制作一个博客阅读器应用程序,从CoreData中保存和获取数据。我可以将JSON结果保存到CoreData中,但是当我试图检索它以在tableView中显示时,它会崩溃,出现
致命错误:在第行展开可选值时意外发现nil

let entity=NSEntityDescription.entityForName(“Blog”,inManagedObjectContext:self.managedObjectContext!)

这是我的密码:

import UIKit
import CoreData

var activeItem:String = ""

class CenterViewController: UIViewController,
  UIWebViewDelegate, NSFetchedResultsControllerDelegate,     
 SidePanelViewControllerDelegate {
 var detailViewController: DetailViewController? = nil
 var managedObjectContext: NSManagedObjectContext? = nil

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var webview2: UIWebView!


var delegate: CenterViewControllerDelegate?

// MARK: Button actions

@IBAction func kittiesTapped(sender: AnyObject) {
delegate?.toggleLeftPanel?()
 }

@IBAction func puppiesTapped(sender: AnyObject) {
delegate?.toggleRightPanel?()
 }

  func animalSelected(animal: Animal) {

var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
var newBlogItem:NSManagedObject
let session = NSURLSession.sharedSession()
var error : NSError?

 let task = session.dataTaskWithURL(animal.url!, completionHandler: {data, response, error -> Void in

    if (error != nil){
        println(error)

    }else{


       let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        var posts = [[String:String]()]

        var post:AnyObject

        var authorDictionary:AnyObject
        var newBlogItem:NSManagedObject
        for var i = 0; i < jsonResult["posts"]!.count; i++

        {
        posts.append([String:String]())
        post = jsonResult["posts"]![i] as NSDictionary
        posts[i]["title"] = post["title"] as? NSString
        posts[i]["publishedDate"] = post["date"] as? NSString
        posts[i]["content"] = post["content"] as? NSString
        authorDictionary = post["author"] as NSDictionary
        posts[i]["author"] = post["name"] as? NSString



            newBlogItem = NSEntityDescription.insertNewObjectForEntityForName("Blog", inManagedObjectContext: context) as NSManagedObject
            newBlogItem.setValue(posts[i]["title"], forKey: "title")
            newBlogItem.setValue(posts[i]["publishedDate"], forKey: "publishedDate")
            newBlogItem.setValue(posts[i]["content"], forKey: "content")
            newBlogItem.setValue(posts[i]["author"], forKey: "author")

            context.save(nil)

        }
        var request = NSFetchRequest(entityName: "Blog")
        request.returnsObjectsAsFaults = false
        var results = context.executeFetchRequest(request, error: nil)
        println(results)

  }

})

task.resume()
   delegate?.collapseSidePanels?()
}

// MARK: - Table View

 func numberOfSectionsInTableView(tableView: UITableView) -> Int {


    return self.fetchedResultsController.sections!.count
  // return 1
}

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
   return sectionInfo.numberOfObjects
   //return 20
}

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
  // self.configureCell(cell, atIndexPath: indexPath)
   cell.textLabel?.text = "blog item"
    return cell
}

 func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}

 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        let context = self.fetchedResultsController.managedObjectContext
        context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject)

        var error: NSError? = nil
        if !context.save(&error) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }
    }
}

func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
    let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
    cell.textLabel?.text = object.valueForKey("title")!.description
}



// MARK: - Fetched results controller

var fetchedResultsController: NSFetchedResultsController {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
        }

        let fetchRequest = NSFetchRequest()
        // Edit the entity name as appropriate.
    let entity = NSEntityDescription.entityForName("Blog", inManagedObjectContext:self.managedObjectContext!)
        fetchRequest.entity = entity?

        // Set the batch size to a suitable number.
        fetchRequest.fetchBatchSize = 20

        // Edit the sort key as appropriate.
        let sortDescriptor = NSSortDescriptor(key: "publishedDate", ascending: false)
        let sortDescriptors = [sortDescriptor]

        fetchRequest.sortDescriptors = [sortDescriptor]

        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Slide Out Tutorial")
        aFetchedResultsController.delegate = self
        _fetchedResultsController = aFetchedResultsController

        var error: NSError? = nil
        if !_fetchedResultsController!.performFetch(&error) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }

        return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil

func controllerWillChangeContent(controller: NSFetchedResultsController) {
    self.tableview.beginUpdates()
}

func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
    switch type {
    case .Insert:
        self.tableview.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
    case .Delete:
        self.tableview.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
    default:
        return
    }
}

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) {
    switch type {
    case .Insert:
        tableview.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
    case .Delete:
        tableview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    case .Update:
        self.configureCell(tableview.cellForRowAtIndexPath(indexPath)!, atIndexPath: indexPath)
    case .Move:
        tableview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        tableview.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
    default:
        return
    }
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    self.tableview.endUpdates()
}
导入UIKit
导入CoreData
var activeItem:String=“”
类CenterViewController:UIViewController,
UIWebViewDelegate,NSFetchedResultsControllerDelegate,
侧面板ViewControllerDelegate{
var detailViewController:detailViewController?=nil
var managedObjectContext:NSManagedObjectContext?=nil
@IBVAR弱var标题标签:UILabel!
@IBVAR表格视图:UITableView!
@ibvar-webview 2:UIWebView!
var代理:CenterViewControllerDelegate?
//标记:按钮操作
@iAction func kittiesTapped(发送方:AnyObject){
代理?.toggleLeftPanel?()
}
@iAction func(发送方:AnyObject){
代理?.toggleRightPanel?()
}
func animalSelected(动物:动物){
var appDel:AppDelegate=UIApplication.sharedApplication().delegate为AppDelegate
变量上下文:NSManagedObjectContext=appDel.managedObjectContext!
var newBlogItem:NSManagedObject
let session=NSURLSession.sharedSession()
var错误:N错误?
让task=session.dataTaskWithURL(animal.url!,completionHandler:{data,response,error->Void in
如果(错误!=nil){
println(错误)
}否则{
将jsonResult=NSJSONSerialization.JSONObjectWithData(数据,选项:NSJSONReadingOptions.MutableContainers,错误:nil)设为NSDictionary
var posts=[[String:String]()]
var post:AnyObject
var authorDictionary:AnyObject
var newBlogItem:NSManagedObject
对于var i=0;iInt{
返回self.fetchedResultsController.sections!.count
//返回1
}
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
让sectionInfo=self.fetchedResultsController.sections![section]作为NSFetchedResultsSectionInfo
返回sectionInfo.numberOfObjects
//返回20
}
func tableView(tableView:UITableView,cellForRowAtIndexPath:nsindepath)->UITableView单元格{
将cell=tableView.dequeueReusableCellWithIdentifier(“cell”,forIndexPath:indexPath)设为UITableViewCell
//self.configureCell(cell,atIndexPath:indexPath)
cell.textlab?.text=“博客项目”
返回单元
}
func tableView(tableView:UITableView,canEditRowAtIndexPath-indepath:nsindepath)->Bool{
//如果不希望指定的项可编辑,则返回false。
返回真值
}
func tableView(tableView:UITableView,CommittedItingStyle编辑样式:UITableViewCellEditingStyle,forRowAtIndexPath indexPath:NSIndexPath){
如果editingStyle==.Delete{
让context=self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath)作为NSManagedObject)
变量错误:n错误?=nil
if!context.save(&错误){
//将此实现替换为适当处理错误的代码。
//abort()导致应用程序生成崩溃日志并终止。您不应该在装运应用程序中使用此函数,尽管它在开发过程中可能很有用。
//println(“未解决的错误\(error),\(error.userInfo)”)
中止
}
}
}
func configureCell(单元格:UITableViewCell,atIndexPath indexPath:NSIndexPath){
让object=self.fetchedResultsController.objectAtIndexPath(indexPath)作为NSManagedObject
cell.textlab?.text=object.valueForKey(“标题”)!.description
}
//标记:-获取的结果控制器
var fetchedResultsController:NSFetchedResultsController{
如果_fetchedResultsController!=nil{
return\u fetchedResultsController!
}
让fetchRequest=NSFetchRequest()
//根据需要编辑实体名称。
让entity=NSEntityDescription.entityForName(“Blog”,在managedObjectContext:self.managedObjectContext!)
fetchRequest.entity=实体?
//将批次大小设置为合适的数字。
fetchRequest.fetchBatchSize=20
//根据需要编辑排序键。
让sortDescriptor=NSSortDescriptor(键:“publishedDate”,升序:false)
让sortDescriptor=[sortDescriptor]
fetchRequest.sortDescriptors=[sortDes
var fetchedResultsController: NSFetchedResultsController {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }
    var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    self.managedObjectContext = appDel.managedObjectContext

    let fetchRequest = NSFetchRequest()
    // Edit the entity name as appropriate.
    let entity = NSEntityDescription.entityForName("Blog", inManagedObjectContext:self.managedObjectContext!)
    fetchRequest.entity = entity?
    ...