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

时间:2017-02-23 06:32:56

标签: ios swift uitableview core-data swift2

这是我在网站上的第二个问题,因此对问题格式的任何反馈都表示赞赏。在这里说的是我的问题:

我试图用两个不同的CoreData实体填充此tableview,但我不知道如何去做。起初我尝试创建另一个对象并为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()    
}  
}

1 个答案:

答案 0 :(得分:1)

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

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

如果你希望不同的实体在彼此之间穿插更难,但是可能。

另外,我不知道你为什么要在didSelectRowAtIndexPath中进行一次看似错误的提取。如果数据与该indexPath上的managedObject相关,您应该能够通过关系获得所需的任何数据。