简体   繁体   中英

Passing core data from selected cell in tableview with certain attributes to another VC

So basically what I am trying to do is:

I have in my tableView a Title and SubTitle loaded from core data. When I select the cell, I want attributes that are not shown in that cell but stores in same entity to be passed to 3 different UITextField in my ViewController.

I have my prepareForSegue set up and ready, but I am missing what and how to send those attributes.

This is the code from my tableView

Updated Code with NSFetchedResultsController

class LedData: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

let ReuseIdentifierCell = "CellData"


// MARK: - IBOutlet

@IBOutlet var tableView: UITableView!


// MARK: - Variables
var managedObjectContext: NSManagedObjectContext!


lazy var fetchedResultsController: NSFetchedResultsController = {
    // Initialize Fetch Request
    let fetchRequest = NSFetchRequest(entityName: "Ledinfo")

    // Add Sort Descriptors
    let sortDescriptor = NSSortDescriptor(key: "manufactor", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    // Initialize Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

    // Configure Fetched Results Controller
    fetchedResultsController.delegate = self

    return fetchedResultsController
}()

// MARK: - VC Lifecycle
override func viewDidLoad() {
    super.viewDidLoad()

    do {
        try self.fetchedResultsController.performFetch()
    } catch {
        let fetchError = error as NSError
        print("\(fetchError), \(fetchError.userInfo)")
    }
}



// MARK: -
// MARK: Table View Data Source Methods

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = fetchedResultsController.sections {
        return sections.count
    }

    return 0
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = fetchedResultsController.sections {
        let sectionInfo = sections[section]
        return sectionInfo.numberOfObjects
    }

    return 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifierCell, forIndexPath: indexPath) as! CellData

    // Configure Table View Cell
    configureCell(cell, atIndexPath: indexPath)

    return cell
}

func configureCell(cell: CellData, atIndexPath indexPath: NSIndexPath) {
    // Fetch Record
    let record = fetchedResultsController.objectAtIndexPath(indexPath)

    // Update Cell
    if let manufactorer = record.valueForKey("manufactor") as? String {
        cell.makerName.text = manufactorer

    }

    if let model = record.valueForKey("model") as? String {
        cell.modelName.text = model
    }
}

// MARK: -
// MARK: Table View Delegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
}


    // MARK: -
    // MARK: Fetched Results Controller Delegate Methods
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
        tableView.beginUpdates()
    }

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

    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
        switch (type) {
        case .Insert:
            if let indexPath = newIndexPath {
                tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            }
            break;
        case .Delete:
            if let indexPath = indexPath {
                tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            }
            break;
        case .Update:
            if let indexPath = indexPath {
                let cell = tableView.cellForRowAtIndexPath(indexPath) as! CellData
                configureCell(cell, atIndexPath: indexPath)
            }
            break;
        case .Move:
            if let indexPath = indexPath {
                tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            }

            if let newIndexPath = newIndexPath {
                tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
            }
            break;
        }
    }
}

This si what I have in my viewController that should receive.

var viaSegue1:String!
var viaSegue2:String!
var viaSegue3:String!

and

override func viewDidLoad()
{
    super.viewDidLoad()

panelWidthTextField.text = viaSegue1
panelHightTextField.text = viaSegue2
panelPitchTextField.text = viaSegue3
}

Hope someone can help with this.

What you should do is use an NSFetchedResultsController to manage the data for your table.

A fetched results controller will save you a lot of inconvenience from having to manage your own array(s) of results from a fetch request.

When it's time to pass the information to your destination view controller, you can retrieve the other attributes right from the model object.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let viewController = segue.destinationViewController as? ViewController {
            if let indexPath = tableView.indexPathForSelectedRow {
                let record = fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject // cast this as the type of your entity
                viewController.panelWidth = record.panelWidth
                viewController.panelHeight = record.panelHeight
                viewController.panelPitch = record.panelPitch 
            }
        }
    }
}

Alternately, you could inject the managed object context and object's objectID , then fetch that particular object in your destination view controller.

Also, you make it appear like you're dealing with arrays of two different entities.

var manufactorer = [NSManagedObject]()
var model = [NSManagedObject]()

You should strongly type cast everything, so Swift knows exactly what type of managed object is in an array or set. If you're dealing with an array of Ledinfo types, you should declare it as such.

As an aside, you may want to use more descriptive names than viaSegue1 , and ViewController . This makes your code easier to read, understand, and maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM