Database Reference
In-Depth Information
protocol JournalEntryDelegate {
func didFinishViewController(
viewController: JournalEntryViewController , didSave: Bool )
}
As you can see, the JournalEntryViewController protocol is very short and consists
of only didFinishViewController(_:didSave:) . This function, which the protocol
requires the delegate to implement, indicates that the user is done editing or
viewing a journal entry and whether the changes, if there are any, should be saved.
To understand how didFinishViewController(_:didSave:) works, switch back to
JournalListViewController.swift and find that method:
func didFinishViewController(
viewController: JournalEntryViewController , didSave: Bool ) {
// 1
if didSave {
// 2
var error: NSError ? = nil
let context = viewController. context
context. performBlock ({ () -> Void in
if context. hasChanges && !context. save (&error) {
println ( "Couldn't save: \(error) , \(error?. userInfo ) " )
abort ()
}
// 3
self . coreDataStack . saveContext ()
})
}
// 4
dismissViewControllerAnimated ( true , completion: {})
}
Let's go through this delegate method step by step:
1. First, the code checks the didSave parameter. It is true if the user taps the Save
button instead of the Cancel button. If true , the app needs to save the user's
data.
2. Next, the code saves the JournalEntryViewController context inside of a
performBlock closure. The code sets this context to the main context, which is
redundant since there's only one context, but doesn't change the behavior. Once
you add a child context to the workflow, the JournalEntryViewController context
will be different from the main context, making this code necessary. If the save
fails, the code prints an error message and aborts the app.
Search WWH ::




Custom Search