新核心数据录入后,应用程序在重新启动时崩溃

时间:2015-07-10 12:57:01

标签: ios swift core-data lldb

快速学习这一切的新手。我创建了一个带有核心数据集成的简单任务应用程序,它非常适用。

我想为每个任务添加一个图像,所以我将图像作为二进制数据添加到我的核心数据模型中,添加了一个轻量级的迁移,以及一些添加图像的代码(相机或库)。当我启动应用程序时,我可以添加条目到我的应用程序,一切正常。但是,当我重新启动我的应用程序时,应用程序崩溃并出现错误(lldb)。当我键入bt时,我收到此错误消息:

* thread #1: tid = 0xba2d3, 0x000000010140a43c CoreFoundation`CFStringCreateCopy + 28, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x000000010140a43c CoreFoundation`CFStringCreateCopy + 28
    frame #1: 0x000000010338f70d libswiftCore.dylib`function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Dead> of Swift.String.init (Swift.String.Type)(_cocoaString : Swift.AnyObject) -> Swift.String + 93
    frame #2: 0x00000001033701a3 libswiftCore.dylib`Swift.String.init (Swift.String.Type)(_cocoaString : Swift.AnyObject) -> Swift.String + 19
  * frame #3: 0x0000000100dab7d0 TaskIt`TaskIt.ViewController.tableView (tableView=0x00007fe9f3059400, indexPath=0xc000000000000016, self=0x00007fe9f2640110)(ObjectiveC.UITableView, cellForRowAtIndexPath : ObjectiveC.NSIndexPath) -> ObjectiveC.UITableViewCell + 640 at ViewController.swift:80
    frame #4: 0x0000000100dabcdf TaskIt`@objc TaskIt.ViewController.tableView (TaskIt.ViewController)(ObjectiveC.UITableView, cellForRowAtIndexPath : ObjectiveC.NSIndexPath) -> ObjectiveC.UITableViewCell + 79 at ViewController.swift:0
    frame #5: 0x0000000101ed6a28 UIKit`-[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 508
    frame #6: 0x0000000101eb5248 UIKit`-[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
    frame #7: 0x0000000101ecb8a9 UIKit`-[UITableView layoutSubviews] + 210
    frame #8: 0x0000000101e55a2b UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    frame #9: 0x0000000105b21ec2 QuartzCore`-[CALayer layoutSublayers] + 146
    frame #10: 0x0000000105b166d6 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 380
    frame #11: 0x0000000101e49675 UIKit`-[UIView(Hierarchy) layoutBelowIfNeeded] + 607
    frame #12: 0x0000000101f3645e UIKit`-[UINavigationController _layoutViewController:] + 1135
    frame #13: 0x0000000101f334a8 UIKit`-[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 522
    frame #14: 0x0000000101e35136 UIKit`-[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 209
    frame #15: 0x0000000101e33470 UIKit`+[UIViewAnimationState popAnimationState] + 289
    frame #16: 0x000000010213a076 UIKit`-[UINavigationTransitionView transition:fromView:toView:] + 2569
    frame #17: 0x0000000101f371b0 UIKit`-[UINavigationController _startTransition:fromViewController:toViewController:] + 2984
    frame #18: 0x0000000101f37448 UIKit`-[UINavigationController _startDeferredTransitionIfNeeded:] + 523
    frame #19: 0x0000000101f37f0e UIKit`-[UINavigationController __viewWillLayoutSubviews] + 43
    frame #20: 0x0000000102082715 UIKit`-[UILayoutContainerView layoutSubviews] + 202
    frame #21: 0x0000000101e55a2b UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    frame #22: 0x0000000105b21ec2 QuartzCore`-[CALayer layoutSublayers] + 146
    frame #23: 0x0000000105b166d6 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 380
    frame #24: 0x0000000105b16546 QuartzCore`CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 24
    frame #25: 0x0000000105a82886 QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 242
    frame #26: 0x0000000105a83a3a QuartzCore`CA::Transaction::commit() + 462
    frame #27: 0x0000000101dd3a2d UIKit`-[UIApplication _reportMainSceneUpdateFinished:] + 44
    frame #28: 0x0000000101dd46f1 UIKit`-[UIApplication _runWithMainScene:transitionContext:completion:] + 2648
    frame #29: 0x0000000101dd30d5 UIKit`-[UIApplication workspaceDidEndTransaction:] + 179
    frame #30: 0x0000000104a8f5e5 FrontBoardServices`__31-[FBSSerialQueue performAsync:]_block_invoke_2 + 21
    frame #31: 0x000000010146841c CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #32: 0x000000010145e165 CoreFoundation`__CFRunLoopDoBlocks + 341
    frame #33: 0x000000010145df25 CoreFoundation`__CFRunLoopRun + 2389
    frame #34: 0x000000010145d366 CoreFoundation`CFRunLoopRunSpecific + 470
    frame #35: 0x0000000101dd2b42 UIKit`-[UIApplication _run] + 413
    frame #36: 0x0000000101dd5900 UIKit`UIApplicationMain + 1282
    frame #37: 0x0000000100db40a7 TaskIt`main + 135 at AppDelegate.swift:13
    frame #38: 0x000000010445f145 libdyld.dylib`start + 1

我的代码:

@IBAction func addPhotoButtonTapped(sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
            var cameraController = UIImagePickerController()
            cameraController.delegate = self
            cameraController.sourceType = UIImagePickerControllerSourceType.Camera

            let mediaTypes:[AnyObject] = [kUTTypeImage]
            cameraController.mediaTypes = mediaTypes
            cameraController.allowsEditing = false

            self.presentViewController(cameraController, animated: true, completion: nil)
        }
        else if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {

            var photoLibraryController = UIImagePickerController()
            photoLibraryController.delegate = self
            photoLibraryController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

            let mediaTypes:[AnyObject] = [kUTTypeImage]
            photoLibraryController.mediaTypes = mediaTypes
            photoLibraryController.allowsEditing = false

            self.presentViewController(photoLibraryController, animated: true, completion: nil)
        }
        else {
            var alertController = UIAlertController(title: "Alert", message: "Your device does not support the camera or photo Library", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }

    //UIImagePickerControllerDelegate

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let imageData = UIImageJPEGRepresentation(image, 1.0)

        let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        let entityDescription = NSEntityDescription.entityForName("TaskModel", inManagedObjectContext: managedObjectContext!)
        let feedItem = TaskModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)

        bgImage = UIImageView(image: image)
        bgImage.frame = CGRectMake(0,0,100,200)
        self.view.addSubview(bgImage)

        (UIApplication.sharedApplication().delegate as! AppDelegate).saveContext()

        self.dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func addTaskButtonTapped(sender: UIButton) {

        let appDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)

        let managedObjectContext = appDelegate.managedObjectContext
        let entityDescription = NSEntityDescription.entityForName("TaskModel", inManagedObjectContext: managedObjectContext!)
        let task = TaskModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
        task.task = taskTextField.text
        task.subtask = subtaskTextField.text
        task.date = dueDatePicker.date
        task.completed = false

        let imageNSData = UIImageJPEGRepresentation(bgImage.image, 1.0);
        task.image = imageNSData;

        appDelegate.saveContext()

        var request = NSFetchRequest(entityName: "TaskModel")
        var error:NSError? = nil

        var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!

        for res in results {
            println(res)
        }


        self.dismissViewControllerAnimated(true, completion: nil)
    }

的ViewController

import UIKit
import CoreData


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

    @IBOutlet weak var tableView: UITableView!

    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
    var fetchedResultsController:NSFetchedResultsController = NSFetchedResultsController()

    var imageViewRow:UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        fetchedResultsController = getFetchedResultsController()
        fetchedResultsController.delegate = self
        fetchedResultsController.performFetch(nil)

    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "showDetailTask" {
            let detailVC: DetailViewController = segue.destinationViewController as! DetailViewController
            let indexPath = self.tableView.indexPathForSelectedRow()
            let thisTask = fetchedResultsController.objectAtIndexPath(indexPath!) as! TaskModel
            detailVC.detailTaskModel = thisTask
        }
        else if segue.identifier == "showTaskAdd" {
            let addTaskVC:AddTaskViewController = segue.destinationViewController as! AddTaskViewController
        }
    }

    @IBAction func addButtonTapped(sender: UIBarButtonItem) {
        self.performSegueWithIdentifier("showTaskAdd", sender: self)
    }




    //UITableViewDataSource

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return fetchedResultsController.sections!.count
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return fetchedResultsController.sections![section].numberOfObjects
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let thisTask = fetchedResultsController.objectAtIndexPath(indexPath) as! TaskModel

        //println(thisTask)

        var cell: TaskCell = tableView.dequeueReusableCellWithIdentifier("myCell") as! TaskCell

        cell.taskLabel.text = thisTask.task
        cell.descriptionLabel.text = thisTask.subtask
        cell.dateLabel.text = Date.toString(date: thisTask.date)

        return cell
    }

    //UITableViewDelegate

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        println(indexPath.row)

        performSegueWithIdentifier("showDetailTask", sender: self)
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 25
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "To do"
        }
        else {
            return "Completed"
        }
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        let thisTask = fetchedResultsController.objectAtIndexPath(indexPath) as! TaskModel

        if indexPath.section == 0 {
            thisTask.completed = true
        }
        else {
            thisTask.completed = false
        }
        (UIApplication.sharedApplication().delegate as! AppDelegate).saveContext()
    }

    // NSFetchedResultsControllerDelegate

    func controllerDidChangeContent(controller: NSFetchedResultsController) {
        tableView.reloadData()
    }

    //Helper


    func taskFetchRequest() -> NSFetchRequest {
        let fetchRequest =  NSFetchRequest(entityName: "TaskModel")
        let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
        let completedDescriptor = NSSortDescriptor(key: "completed", ascending: true)
        fetchRequest.sortDescriptors = [completedDescriptor, sortDescriptor]

        return fetchRequest
    }

    func getFetchedResultsController() -> NSFetchedResultsController {

        fetchedResultsController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: "completed", cacheName: nil)

        return fetchedResultsController
    }
}

希望有人能把我带到正确的方向。

谢谢!

0 个答案:

没有答案