Lynn_Yang
Lynn_Yang

Reputation: 167

How to write into the CoreData entity at the same index in different view controller (also swift files)

I have created core data using 'NSFetchedResultController' and 'managedObjectContext' in a table view. But in the later view controller, after gathering accelerometer data and conduct calculation, I will get some results that I also want to store in the same row index with the core data I created before.

How can I achieve this? If I create managedObjectContext again, it will create another 'row' of core data in this table.

The code in tableViewController:

'
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext

var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()

override func viewDidLoad() {
    super.viewDidLoad()

    fetchedResultController = getFetchedResultController()
    fetchedResultController.delegate = self
    fetchedResultController.performFetch(nil)

}

func getFetchedResultController() -> NSFetchedResultsController {
    fetchedResultController = NSFetchedResultsController(fetchRequest: trialFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
    return fetchedResultController
}

func trialFetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Trials")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
    return fetchRequest
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

   override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    let numberOfSections = fetchedResultController.sections?.count
    return numberOfSections!
}

   override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
return numberOfRowsInSection!  
}

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    let trial = fetchedResultController.objectAtIndexPath(indexPath) as Trials
    cell.textLabel?.text = trial.trialName
    cell.detailTextLabel?.text = trial.date?.description

    return cell
}

 override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as NSManagedObject

         managedObjectContext?.deleteObject(managedObject)
         managedObjectContext?.save(nil)
    }

func controllerDidChangeContent(controller: NSFetchedResultsController!) {
        tableView.reloadData()
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "showTrial" {
        let indexPath = tableView.indexPathForSelectedRow()
        let trial:Trials = fetchedResultController.objectAtIndexPath(indexPath!) as Trials

        let trialController:TrialDetailViewController = segue.destinationViewController as TrialDetailViewController

            trialController.trial = trial
      }

    }

'

The code in the createTrial Controller:

' let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "createTrial"  {
        if theTrialName.text != "" {
            createTrial()
        } else {

            let alertView = UIAlertController(title: "", message: "Trial name couldn't be empty", preferredStyle: .Alert)
            alertView.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            presentViewController(alertView, animated: true, completion: nil)

        }
    }
}

func createTrial() {
    let entityDescripition = NSEntityDescription.entityForName("Trials", inManagedObjectContext: managedObjectContext!)
    let trial = Trials(entity: entityDescripition!, insertIntoManagedObjectContext: managedObjectContext)
    trial.trialName = theTrialName.text
    trial.location = theLocation.text
    trial.notes = theNotes.text

    if theArm.on {
        trial.arm = 1
    } else {
        trial.arm = 0
    }
    managedObjectContext?.save(nil)
}

'

ps. the view controller I want to get data from is not this following segue, it is around 3 view afterwards. And I have created a string to store the data I need in that view.

Upvotes: 0

Views: 72

Answers (1)

Lynn_Yang
Lynn_Yang

Reputation: 167

I solved the problem by creating the object in the tableViewControllerand use segue twice to transmit it to secondViewControllerand thirdViewController. So it will be at the same index for the whole time. And I can change the content of the core data at both the following view controllers.

Upvotes: 0

Related Questions