为啥我的视图控制器没有检索到我的 CoreData 对象

Posted

技术标签:

【中文标题】为啥我的视图控制器没有检索到我的 CoreData 对象【英文标题】:Why Are My CoreData Objects Not Being Retrieved By My View Controller为什么我的视图控制器没有检索到我的 CoreData 对象 【发布时间】:2016-01-09 20:55:18 【问题描述】:

所以我有这个xCode 项目,我正在开发一个使用Swift 语言的iPhone 应用程序。我正在尝试将两个字符串和二进制数据图像存储在核心数据中的一个对象中,我可以在此viewcontroller 中检索该对象。我用来转换到此视图的表视图显示了正确的项目关联,但是当我加载此视图时,属性没有加载。为什么对象没有被上传并显示到 viewcontroller

import UIKit
import CoreData

class IndividualMainViewController: UIViewController, NSFetchedResultsControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate


    @IBOutlet weak var backCancelButton: UIBarButtonItem!
    @IBOutlet weak var saveEditButton: UIBarButtonItem!

    @IBOutlet weak var deviceImageButton: UIButton!
    @IBOutlet weak var cameraImageButton: UIButton!


    var item: Item? = nil
    let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let frc: NSFetchedResultsController = NSFetchedResultsController()


    @IBOutlet weak var imageHolder: UIImageView!

    @IBOutlet weak var horseName: UITextField!
    @IBOutlet weak var officialName: UITextField!

    override func viewDidLoad()
    
        super.viewDidLoad()


        if(item == nil)
        
            print("item returned nil")
            print(item)
        
        else
        
            print("Object did load")
            self.horseName.text = item?.name
            self.officialName.text = item?.offName
            self.imageHolder.image = UIImage(data: (item?.image)!)

            saveEditButton.title = "Edit"
            backCancelButton.title = "To Barn"

            self.deviceImageButton.hidden = true

            self.cameraImageButton.hidden = true

        

        let tap: UIGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissEditor")
        view.addGestureRecognizer(tap)


    

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

    func dismissEditor()
    
        view.endEditing(true)
    



    @IBAction func addImageFromDevice(sender: AnyObject)
    
        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        pickerController.allowsEditing = true

        self.presentViewController(pickerController, animated: true, completion: nil)
    


    @IBAction func addImageFromCamera(sender: AnyObject)
    
        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        pickerController.sourceType = UIImagePickerControllerSourceType.Camera
        pickerController.allowsEditing = true

        self.presentViewController(pickerController, animated: true, completion: nil)
    

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?)
    
        self.dismissViewControllerAnimated(true, completion: nil)

        self.imageHolder.image = image
    



    @IBAction func saveEditTapped(sender: AnyObject)
    
        if(saveEditButton.title == "Save")
        
            if item != nil
            
                editItem()

                print("Item edit saved")

                saveEditButton.title = "Edit"
                backCancelButton.title = "To Barn"
            
            else
            
                createNewItem()

                print("New item created")

                performSegueWithIdentifier("back", sender: nil)
            
        
        else
        
            saveEditButton.title = "Save"
            backCancelButton.title = "Cancel"
            print("Not saved")
        
    



    func createNewItem()
    
        let entityDescription = NSEntityDescription.entityForName("Item", inManagedObjectContext: moc)

        let item = Item(entity: entityDescription!, insertIntoManagedObjectContext: moc)

        item.name = horseName.text
        item.offName = officialName.text
        item.image = UIImagePNGRepresentation(imageHolder.image!)

        do
        
            try self.moc.save()
        
        catch
        
            print("Failed ot create new object")
            return
        
    



    func editItem()
    
        item?.name = horseName.text
        item?.offName = officialName.text
        item!.image = UIImagePNGRepresentation(imageHolder.image!)

        do
        
            try self.moc.save()
        
        catch
        
            print("Failed to save item")
            return
        
    

【问题讨论】:

【参考方案1】:

仅使用泛型初始化器初始化NSFetchedResultsController 是不够的。

您必须告诉控制器要做什么、使用哪个托管对象上下文、设置委托并执行初始提取。

Swift 中常用的方法是将控制器声明为惰性计算变量。

lazy var fetchedResultsController: NSFetchedResultsController = 

  let fetchRequest = NSFetchRequest()
  let entity = NSEntityDescription.entityForName(self.entity, inManagedObjectContext: self.managedObjectContext)
  fetchRequest.entity = entity
  fetchRequest.predicate = self.fetchPredicate

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

  // Edit the sort key as appropriate.
  fetchRequest.sortDescriptors = [self.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: nil)
  aFetchedResultsController.delegate = self

  do 
    try aFetchedResultsController.performFetch()
   catch let error as NSError 
    print(error)
  

  return aFetchedResultsController
()

用你的值替换实例变量(以self.开头)表示的所有参数

【讨论】:

以上是关于为啥我的视图控制器没有检索到我的 CoreData 对象的主要内容,如果未能解决你的问题,请参考以下文章

为啥 CoreData 不保存任何东西?

尝试使用自动布局将 UIButton 添加到我的视图中,但它没有出现。为啥? [关闭]

将 facebook 的联系人检索到我的应用程序中并在表格视图中显示?

UITableView 与 Xcode,获取 CoreData 问题

核心数据 - 保存和检索属性 - 示例代码

当我尝试快速加载我的表格视图时,为啥会出现 EXC_BAD_INSTRUCTION 错误?