Swift 2:使用两个 CoreData 实体填充 TableView

Swift 2: Populating a TableView with two CoreData entities

这是我在网站上提出的第二个问题,因此欢迎任何有关问题格式的反馈。话虽如此,这是我的问题:

我正在尝试用两个不同的 CoreData 实体填充此表视图,但我不知道该怎么做。起初我尝试创建另一个对象并为 tableview 执行必要的方法,但它没有用。我试图用来自另一个实体的数据填充它,但我无法让 tableview 显示来自第二个实体的信息。我想知道这样做是否有任何已知的约定。任何帮助深表感谢。

import UIKit
import CoreData

class DataEntryTableViewController: UITableViewController{

@IBOutlet weak var menuButton: UIBarButtonItem!

@IBOutlet var listaMiembros: UITableView!

var object = [NSManagedObject]()

var dictionary: [String:String] = [
    "tipoVehiculo" :"",
    "ocupantes" :"",
    "numDeTablilla" :"",
    "jurisdiccion": "",
    "estado" :"",
    "vin" :"",
    "year" :"",
    "marca": "",
    "model" :"",
    "marbete" :"",
    "aseguradora" :"",
    "fechaCompra": "",
    "fechaExpiracion": "",
   ]

var objectNum = -1

@IBOutlet weak var listaMembers: UITableViewCell!
override func viewDidLoad() {

  super.viewDidLoad()
  listaMiembros.delegate = self
  listaMiembros.dataSource = self

    // Do any additional setup after loading the view, typically from a nib.
    //ADD SCROLL VIEW DIMENTIONS

    if revealViewController() != nil {
        menuButton.target = revealViewController()
      //  menuButton.action = "revealToggle:"
           menuButton.action = #selector(SWRevealViewController.revealToggle(_:))

        tableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "Cell")

    }
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

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

    let managedContext = appDelegate.managedObjectContext

    //2       
    let fetchRequest = NSFetchRequest(entityName: "PageFour")

    //3
    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        object = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

    self.tableView.reloadData()
    objectNum = -1
 }

// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return object.count
}

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

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
    let person = object[indexPath.row]
    cell!.textLabel!.text = person.valueForKey("numDeTablilla") as? String
   return cell!
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let indexPath = tableView.indexPathForSelectedRow // index path of selected cell

    let cellIndex = indexPath!.row // index of selected cell
    // print(indexPath?.row)//iT'S THE NUMBER YOU WANT - 1
    let cellName = tableView.cellForRowAtIndexPath(indexPath!) //  instance of selected cell
    objectNum = cellIndex + 1
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext
    let request = NSFetchRequest(entityName: "PageFour")
    request.returnsObjectsAsFaults = false
    do {
        try context.save()
    } catch {
        print("There was a problem!")
    }

    do {
        let results = try context.executeFetchRequest(request)
        if results.count > 0 {

            for result in results as! [NSManagedObject] {

                if cellName?.textLabel?.text == result.valueForKey("numDeTablilla") as? String{

                    dictionary["numDeTablilla"] = result.valueForKey("numDeTablilla") as? String
                    dictionary["marca"] = result.valueForKey("marcaField") as? String
                    dictionary["model"] = result.valueForKey("modeloField") as? String
                    dictionary["year"] = result.valueForKey("yearField") as? String
                    dictionary["tipoVehiculo"] = result.valueForKey("tipoVehiculo") as? String
                    dictionary["ocupantes"] = result.valueForKey("ocupantes") as? String
                    dictionary["jurisdiccion"] = result.valueForKey("jurisdicionVehiculo") as? String
                    dictionary["estado"] = result.valueForKey("estadoField") as? String
                    dictionary["vin"] = result.valueForKey("vinField") as? String
                    dictionary["marbete"] = result.valueForKey("numeroDeMarbete") as? String
                    dictionary["aseguradora"] = result.valueForKey("aseguradoraField") as? String
                    dictionary["fechaCompra"] = result.valueForKey("fechaCompraField") as? String
                    dictionary["fechaExpiracion"] = result.valueForKey("FechaExpiracionField") as? String

                }
            }
            performSegueWithIdentifier("EditVehicle", sender: self)
        }

    } catch {
        print("Fetch Failed")
    }
}

 @IBAction func unwindToVC(segue: UIStoryboardSegue) {
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "EditVehicle"){
        //prepare for segue to the details view controller

        if let detailsVC = segue.destinationViewController as? NewVehicleController {
            // let indexPath = self.tableView.indexPathForSelectedRow

            detailsVC.dictionary = self.dictionary
            detailsVC.objectNum = self.objectNum
        }
    }
    //unnecessary for now
//        if(segue.identifier == "gotoNewData"){
//            if let detailsVC = segue.destinationViewController as?         NewDataEntryTableViewController {
//                //detailsVC.dictionary = self.dictionary
//                detailsVC.objectNum = self.objectNum
//            }
//        }
    self.tableView.reloadData()    
}  
}

首先,不要保留 managedObjects。如果 object 从数据库中删除访问它会导致崩溃。最好使用自动跟踪插入、删除和更改的fetchedResultsController

解决您问题的最简单方法是在一个部分中使用一种类型的实体,在不同的部分中使用另一种类型的实体。 (您不需要 header 部分,因此它可以显示为一个部分)。您必须有两个不同的 fetchedResultsController - 每个部分一个。而且你必须小心地将你的 tableview indexPath 转换为正确的 fetchedResultsController indexPath - 但如果你只有两个部分,那就没那么难了。

如果你想让不同的实体相互穿插,要难得多,但这是可能的。

此外,我不知道您为什么在 didSelectRowAtIndexPath 中进行提取,这似乎是错误的。如果数据与该 indexPath 处的 managedObject 相关,您应该能够通过关系获取所需的任何数据。