这是我的代码:

import UIKit
import CoreData

class PhotoList: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
    fetchedResultsController?.delegate = self
    fetchedResultsController?.performFetch(nil)

    tableView.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


@IBOutlet var tableView: UITableView!
var whoTookArray: [String] = []
var imageArray: [UIImage] = []
let moc:NSManagedObjectContext? = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController?
var whoTookName: String = ""


func fetchRequest() -> NSFetchRequest {
    var request = NSFetchRequest(entityName:"PhotoListEntity")
    let sortDescriptor = NSSortDescriptor(key: "whoTook", ascending: true)
    request.predicate = nil
    request.sortDescriptors = [sortDescriptor]
    request.fetchBatchSize = 20
    return request
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    if let let whoTookName = fetchedResultsController?.objectAtIndexPath(indexPath) as? PhotoListEntity {
        cell.textLabel?.text = whoTookName.whoTook
    }
    return cell
}

//NSFetchedResultsController Delegate functions

func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type:NSFetchedResultsChangeType) {

    switch type {

    case NSFetchedResultsChangeType.Insert:
        tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade)
        break

    case NSFetchedResultsChangeType.Delete:
        tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade)
        break

    case NSFetchedResultsChangeType.Move:
        break

    case NSFetchedResultsChangeType.Update:
        break

    default:
        break
    }
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    }
    switch editingStyle {
    case .Delete:
        moc?.deleteObject(fetchedResultsController?.objectAtIndexPath(indexPath) as! PhotoListEntity)
    case .Insert:
        break
    case .None:
        break
    }
}

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

    switch type {
    case NSFetchedResultsChangeType.Insert:
        tableView.insertRowsAtIndexPaths(NSArray(object: newIndexPath!) as [AnyObject], withRowAnimation: UITableViewRowAnimation.Fade)
        break

    case NSFetchedResultsChangeType.Delete:
        tableView.deleteRowsAtIndexPaths(NSArray(object: newIndexPath!) as [AnyObject], withRowAnimation: .Fade)
        break

    case NSFetchedResultsChangeType.Move:
        tableView.deleteRowsAtIndexPaths(NSArray(object: newIndexPath!) as [AnyObject], withRowAnimation: .Fade)
        break

    case NSFetchedResultsChangeType.Update:
        tableView.cellForRowAtIndexPath(indexPath!)
        break

    default:
        break
    }
}

func controllerWillChangeContent(controller: NSFetchedResultsController) {
    tableView.beginUpdates()
}

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

}




import UIKit
import CoreData

protocol sendDetailsDelegate {
    func sendDetails(name: String)
}

class Details: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate, NSFetchedResultsControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
        tapGestureRecognizer.numberOfTapsRequired = 1
        imageSelected.addGestureRecognizer(tapGestureRecognizer)
        imageSelected.userInteractionEnabled = true
    }

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


    @IBOutlet var whoTookTextField: UITextField!
    @IBOutlet var imageSelected: UIImageView!
    let moc: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!



    //Pick the image by tapping, accessing the PhotoLibrary
    func chooseImage(recognizer: UITapGestureRecognizer) {
        let imagePicker: UIImagePickerController = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        self.presentViewController(imagePicker, animated: true, completion: nil)
    }

    //Put the selected image into the screen
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

        let pickedImage: UIImage = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
        let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(288,148))
        var sizeOfImageView: CGRect = imageSelected.frame
        sizeOfImageView.size = smallPicture.size
        imageSelected.frame = sizeOfImageView
        imageSelected.image = smallPicture
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

    func scaleImageWith(image: UIImage, newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        image.drawInRect(CGRectMake(0,0, newSize.width, newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }


    @IBAction func addButton(sender: AnyObject) {

        if whoTookTextField == nil || imageSelected == nil { return }
        if imageSelected == nil { return }

        let entityDescription = NSEntityDescription.entityForName("PhotoListEntity", inManagedObjectContext: moc)
        let name = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: moc)
        name.setValue(whoTookTextField.text, forKey: "whoTook")


        if let navigation = self.navigationController {
            navigation.popViewControllerAnimated(true)
        }
    }
}



and this is my CoreData model:



import Foundation
import CoreData

@objc(PhotoListEntity)
class PhotoListEntity: NSManagedObject {

    @NSManaged var whoTook: String
    @NSManaged var relationship: PhotoListEntity

}


我对此并不陌生,对此我感到抱歉。我想知道为什么当我再次关闭并打开该应用程序时为什么不保存它。谢谢!!!!

答案已经发布!谢谢大家的想法! :D

最佳答案

添加此功能:

func save() {
        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        var moc: NSManagedObjectContext = appDel.managedObjectContext!
        var whoTook: AnyObject! = NSEntityDescription.insertNewObjectForEntityForName("PhotoListEntity", inManagedObjectContext: moc)
        var error: NSError?
        moc.save(nil)
    }


并在addButton中调用它!做完了! :D

10-08 05:35