使用CoreData存储

时间:2015-07-29 21:34:36

标签: ios uitableview core-data

我的应用程序非常简单:我有一个tableview来存储recipe *名称,并且对于每个食谱名称,还有另一个tableview,每个食谱都有几个*成分。

我已经设法用CoreData保存了名称和成分,但问题是:当我按下添加新食谱名称并进入成分表视图区域时,为上一个食谱保存的成分就在那里!如何清除表视图以启动新视图?

此外,我的表格视图没有立即更新,我必须关闭应用程序并再次打开它。我该如何解决?

注意:如果我的问题太难理解,我可以发布一些代码!在此先感谢,大家=)

修改

代码:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

    @IBOutlet var tableView: UITableView!
    var imageList: [UIImage] = []
    var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    var fetchedResultsController: NSFetchedResultsController?

    override func viewDidLoad() {
        fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchName(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
        fetchedResultsController?.delegate = self
        fetchedResultsController?.performFetch(nil)
        tableView.reloadData()
    }

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


    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("recipeCell", forIndexPath: indexPath) as! UITableViewCell
        if let recipeCell = fetchedResultsController?.objectAtIndexPath(indexPath) as? Details {
            cell.textLabel?.text = recipeCell.name
        }
        return cell 
    }
}

-

import UIKit
import CoreData

class InfoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate {


    @IBOutlet var nameField: UITextField!
    @IBOutlet var imageView: UIImageView!
    var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    override func viewDidLoad() {
        super.viewDidLoad()

        //Pick the image by tap
        let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
        tapGestureRecognizer.numberOfTapsRequired = 1
        imageView.addGestureRecognizer(tapGestureRecognizer)
        imageView.userInteractionEnabled = true

    }

    //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
        // small picture
        let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(288,148))
        var sizeOfImageView:CGRect = imageView.frame
        sizeOfImageView.size = smallPicture.size
        imageView.frame = sizeOfImageView
        imageView.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) {

        let entityDescription = NSEntityDescription.entityForName("Details", inManagedObjectContext: moc!)
        let details = Details(entity: entityDescription!, insertIntoManagedObjectContext: moc)
        details.name = nameField.text

        var error: NSError?
        moc?.save(&error)

        if let err = error {
            var status = err.localizedFailureReason
            println("\(status)")
        } else {
            println("Ingredient \(nameField.text) saved successfully!")
        }
            if let navigation = navigationController {
            navigation.popViewControllerAnimated(true)

        }
    }
}

-

import UIKit
import CoreData

class IngredientListViewController: UIViewController, NSFetchedResultsControllerDelegate {

    @IBOutlet var tableView: UITableView!
    var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    var fetchedResultsController: NSFetchedResultsController?

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchIngredient(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
        fetchedResultsController?.delegate = self
        fetchedResultsController?.performFetch(nil)
        tableView.reloadData()
    }

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

    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("ingCell", forIndexPath: indexPath) as! UITableViewCell
        if let recipeCell = fetchedResultsController?.objectAtIndexPath(indexPath) as? Ingredients {
            cell.textLabel?.text = recipeCell.ingredients
        }
        return cell
    }
}

-

import UIKit
import CoreData

class IngredientViewController: UIViewController {


    @IBOutlet var nameField: UITextField!
    var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext



    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func addButton(sender: AnyObject) {

        let entityDescription = NSEntityDescription.entityForName("Ingredients", inManagedObjectContext: moc!)
        let details = Ingredients(entity: entityDescription!, insertIntoManagedObjectContext: moc)
        details.ingredients = nameField.text

        var error: NSError?
        moc?.save(&error)

        if let err = error {
            var status = err.localizedFailureReason
            println("\(status)")
        } else {
            println("Ingredient \(nameField.text) saved successfully!")
        }
        if let navigation = navigationController {
            navigation.popViewControllerAnimated(true)

        }
    }
}

和模特:

import Foundation
import CoreData

class Ingredients: NSManagedObject {

    @NSManaged var ingredients: String
    @NSManaged var relationship: NSSet

}

import Foundation
import CoreData

class Details: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var relationship: Ingredients

}

1 个答案:

答案 0 :(得分:2)

概述:

  1. 您需要修改模型:目前每个Details对象只能有一个Ingredients。我怀疑你需要这种关系才能成为很多人的关系。所以食谱可以有很多成分。
  2. 您需要向Details?添加var(类型为IngredientListViewController)。这将代表所选的食谱。 (例如var chosenRecipe : Details?
  3. fetchIngredient中,您需要为获取添加谓词,以将结果限制为所选配方。例如。 fetch.predicate = NSPredicate(format:"ANY relationship == %@", chosenRecipe)
  4. 在转换到此VC之前,您需要设置chosenRecipe(可能在前面的表视图中的prepareForSegue或didSelectRowAtIndexPath中)。
  5. 要让您的电视自动更新,请使用fetchedResultsController委托方法。 (你实施了这些吗?)