
我必须在我的代码中进行更改(显然)并且能够解决它,但是在这种情况下我不能.这是我的代码:
import UIKitimport CoreDataclass AddtableVIEwController: UItableVIEwController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet weak var nameTextFIEld:UITextFIEld! @IBOutlet weak var locationTextFIEld:UITextFIEld! @IBOutlet weak var imageVIEw:UIImageVIEw! @IBOutlet weak var notesVIEw:UITextVIEw! var coreDataStack = (UIApplication.sharedApplication().delegate as AppDelegate).coreDataStack var backpackerSpot:BackpackerSpot! var managedContext: NSManagedobjectContext! overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() } overrIDe func dIDReceiveMemoryWarning() { super.dIDReceiveMemoryWarning() // dispose of any resources that can be recreated. } // Todo Give user the choice of the Photo library or the Camera overrIDe func tableVIEw(tableVIEw: UItableVIEw,dIDSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { if UIImagePickerController.isSourceTypeAvailable(.Camera) { let imagePicker = UIImagePickerController() imagePicker.allowsEditing = false imagePicker.delegate = self imagePicker.sourceType = .Camera self.presentVIEwController(imagePicker,animated: true,completion: nil) } } tableVIEw.deselectRowAtIndexPath(indexPath,animated: true) } // FIXME image is being displayed in landscape if it is taken in portrait mode by default func imagePickerController(picker: UIImagePickerController!,dIDFinishPickingImage image: UIImage!,editingInfo: [NSObject : AnyObject]!) { imageVIEw.image = image imageVIEw.contentMode = UIVIEwContentMode.ScaleAspectFill imageVIEw.clipsToBounds = true dismissVIEwControllerAnimated(true,completion: nil) } @IBAction func save() { //valIDation var errorFIEld = "" // Todo have placeholder text in the NOTES fIEld match up with the placholder text in the name and LOCATION fIElds. if nameTextFIEld.text == "" { errorFIEld = "name" } else if locationTextFIEld.text == "" { errorFIEld = "location" } else if notesVIEw.text == "" { errorFIEld = "notes" } if errorFIEld != "" { let alertController = UIAlertController(Title: "Error",message: "You must fill in \(errorFIEld).",preferredStyle: .Alert) let doneAction = UIAlertAction(Title: "OK",style: .Default,handler: nil) alertController.addAction(doneAction) self.presentVIEwController(alertController,completion: nil) return } // If all fIElds are correctly filled in,extract the fIEld value // Create Restaurant Object and save to data store// if let managedobjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).coreDataStack.context { let entityBackpackerSpot = NSEntityDescription.entityForname("BackpackerSpot",inManagedobjectContext: coreDataStack.context) backpackerSpot?.spotname = nameTextFIEld.text backpackerSpot?.spotLocation = locationTextFIEld.text backpackerSpot?.spotimage = UIImagePNGRepresentation(imageVIEw.image) backpackerSpot?.spotNote = notesVIEw.text var error: NSError? if !managedContext.save(&error) { println("insert error: \(error!.localizedDescription)") return } // Execute the unwind segue and go back to the home screen performSegueWithIDentifIEr("unwindToHomeScreen",sender: self) }} 该应用程序启动正常,但是当我点击附加到保存功能的UIbutton时,它崩溃了,我收到以下错误:
Fatal error: unexpectedly found nil while unwrapPing an Optional value(lldb)
调试器突出显示的行是:
if !managedContext.save(&error) { 不可否认,我必须花更多时间在Swift中使用Optionals,因为它们似乎常常给我带来麻烦,尽管通常我能够弄明白.如果有人能指出我正确的方向,这将是伟大的.谢谢.
编辑:这是我的核心数据栈:
import Foundationimport CoreDataclass CoreDataStack { let model: NSManagedobjectModel let storeCoordinator: NSPersistentStoreCoordinator let context: NSManagedobjectContext let store: NSPersistentStore? let dbname = "BackpackerSpots" // these options do the migration for us let options = [NSInferMapPingModelautomaticallyOption:true,NSMigratePersistentStoresautomaticallyOption: true] init() { //1 loading model from the file let bundle = NSBundle.mainBundle() let modelURL = bundle.URLForResource(dbname,withExtension: "momd") model = NSManagedobjectModel(contentsOfURL: modelURL!)! //2 store coordinator created using that model storeCoordinator = NSPersistentStoreCoordinator(managedobjectModel: model) //3 context context = NSManagedobjectContext() context.persistentStoreCoordinator = storeCoordinator //4. store let documentsURL = MydocumentDirectory() let storeURL = documentsURL.URLByAppendingPathComponent(dbname) var error:NSError? store = storeCoordinator.addPersistentStoreWithType(NSsqliteStoreType,configuration: nil,URL: storeURL,options: nil,error: &error) if store == nil { println("error adding persistent store: \(error)") abort() } } func saveContext() { var error: NSError? if context.hasChanges && !context.save(&error) { println("Could not save. \(error),\(error?.description)") } }} 编辑:这是我的根视图控制器:
import UIKitimport CoreDataclass BackpackerSpottableVIEwController: UItableVIEwController,NSFetchedResultsControllerDelegate { var coreDataStack = (UIApplication.sharedApplication().delegate as AppDelegate).coreDataStack// var backpackerSpot:BackpackerSpot! var managedContext: NSManagedobjectContext! var backpackerSpots:[BackpackerSpot] = [] var fetchResultController:NSFetchedResultsController! // Let's add some animations! overrIDe func tableVIEw(tableVIEw: UItableVIEw,willdisplayCell cell: UItableVIEwCell,forRowAtIndexPath indexPath: NSIndexPath) { // initial cell state cell.Alpha = 0 // state after animations UIVIEw.animateWithDuration(1.0,animations: { cell.Alpha = 1}) } overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() var fetchRequest = NSFetchRequest(entityname: "BackpackerSpot") let sortDescriptor = NSSortDescriptor(key: "spotname",ascending: true) fetchRequest.sortDescriptors = [sortDescriptor]// if let managedobjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).coreDataStack { let entityBackpackerSpot = NSEntityDescription.entityForname("BackpackerSpot",inManagedobjectContext: coreDataStack.context) fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest,managedobjectContext: coreDataStack.context,sectionnameKeyPath: nil,cachename: nil) fetchResultController.delegate = self var error: NSError? var result = fetchResultController.performFetch(&error) backpackerSpots = fetchResultController.fetchedobjects as [BackpackerSpot] if result != true { println(error?.localizedDescription) } } overrIDe func dIDReceiveMemoryWarning() { super.dIDReceiveMemoryWarning() // dispose of any resources that can be recreated. } // MARK: - table vIEw data source overrIDe func tableVIEw(tableVIEw: UItableVIEw,numberOfRowsInSection section: Int) -> Int { return self.backpackerSpots.count } overrIDe func tableVIEw(tableVIEw: UItableVIEw,cellForRowAtIndexPath indexPath: NSIndexPath) -> UItableVIEwCell { let cellIDentifIEr = "Cell" let cell = tableVIEw.dequeueReusableCellWithIDentifIEr(cellIDentifIEr,forIndexPath: indexPath) as CustomtableVIEwCell let backpackerSpot = backpackerSpots[indexPath.row] cell.nameLabel.text = backpackerSpot.spotname cell.thumbnailImageVIEw.image = UIImage(data: backpackerSpot.spotimage) cell.locationLabel.text = backpackerSpot.spotLocation return cell } overrIDe func tableVIEw(tableVIEw: UItableVIEw,commitEditingStyle editingStyle: UItableVIEwCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) { } overrIDe func tableVIEw(tableVIEw: UItableVIEw,editactionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { var deleteAction = UItableVIEwRowAction(style: UItableVIEwRowActionStyle.Default,Title: "Delete",handler: { (action:UItableVIEwRowAction!,indexPath:NSIndexPath!) -> VoID in// if let managedobjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedobjectContext { let entityBackpackerSpot = NSEntityDescription.entityForname("BackpackerSpot",inManagedobjectContext: self.coreDataStack.context) let backpackerSpottoDelete = self.fetchResultController.objectAtIndexPath(indexPath) as BackpackerSpot self.managedContext.deleteObject(backpackerSpottoDelete) var error: NSError? if !self.managedContext.save(&error) { println("Could not save \(error),\(error?.description)") } }) deleteAction.backgroundcolor = UIcolor(red: 169.0/255.0,green: 37.0/255.0,blue: 50.0/255.0,Alpha: 1.0) return [deleteAction] } func controllerWillChangeContent(controller: NSFetchedResultsController!) { tableVIEw.beginUpdates() } 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: tableVIEw.reloadRowsAtIndexPaths([indexPath],withRowAnimation: .Fade) default: tableVIEw.reloadData() } backpackerSpots = controller.fetchedobjects as [BackpackerSpot] } func controllerDIDChangeContent(controller: NSFetchedResultsController!) { tableVIEw.endUpdates() } overrIDe func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) { if segue.IDentifIEr == "showBackpackerSpotDetails" { if let row = tableVIEw.indexPathForSelectedRow()?.row { let destinationController = segue.destinationVIEwController as DetailVIEwController destinationController.backpackerSpot = backpackerSpots[row] } } } @IBAction func unwindToHomeScreen(segue: UIStoryboardSegue) { }}解决方法 您尚未初始化NSManagedContext变量.使用默认的Core Data设置,您可以执行以下 *** 作: overrIDe func vIEwDIDLoad() { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { managedContext = appDelegate.managedobjectContext } } 编辑:鉴于您的核心数据设置,您应该这样做:
overrIDe func vIEwDIDLoad() { managedContext = coreDataStack.context } 总结 以上是内存溢出为你收集整理的iOS 8核心数据堆栈 – 致命错误:在解包可选值时发现为零全部内容,希望文章能够帮你解决iOS 8核心数据堆栈 – 致命错误:在解包可选值时发现为零所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)