Skip to content

Instantly share code, notes, and snippets.

@grosch
Last active November 5, 2017 06:02
Show Gist options
  • Save grosch/8bd1cbf31c6e8075b727d358b403add2 to your computer and use it in GitHub Desktop.
Save grosch/8bd1cbf31c6e8075b727d358b403add2 to your computer and use it in GitHub Desktop.
Create/edit in a child context
import UIKit
import CoreData
class Ticket: NSManagedObject { }
class TicketListViewController: UITableViewController {
var persistentCoordinator: NSPersistentContainer!
var tickets: [Ticket]!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! TicketEditorViewController
switch segue.identifier! {
case "createNewTicket":
vc.parentContext = persistentCoordinator.viewContext
case "editExistingTicket":
let indexPath = tableView.indexPathForSelectedRow!
vc.ticket = tickets[indexPath.row]
default:
break
}
}
}
final class TicketEditorViewController: UIViewController {
private let editContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
var parentContext: NSManagedObjectContext!
var ticket: Ticket?
override func viewDidLoad() {
super.viewDidLoad()
if let objectId = ticket?.objectID {
// We are editing an existing ticket.
editContext.parent = ticket!.managedObjectContext
ticket = (editContext.object(with: objectId) as! Ticket)
} else {
// We are creating a new ticket.
editContext.parent = parentContext
ticket = Ticket(context: editContext)
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
view.endEditing(true)
if identifier == "done" {
// validate all inputs and return appropriate value
return true
}
return super.shouldPerformSegue(withIdentifier: identifier, sender: sender)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "done", editContext.hasChanges else { return }
try! editContext.save()
try! editContext.parent!.save()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment