It's time to use Core Data, but the open documentation and guides out there spend a lot of time talking about general setup and nitty gritty "behind the scenes" details. Those things are important, but I would love a quick, clean source showing how to actually use information stored in a Core Data model.
The Scenario
In my simple example I have a single entity type:
Job
- salary [Double]
- dateCreated [Date]
This is a Swift iOS app powered by story boards, with the default generated AppDelegate.swift which handles the generation of my Managed Object Context.
The Question
How do I use Job instances in my application?
Bonus points if you can also provide insight around these items:
- As someone who is used to the MVC design pattern, how do I avoid including dirty data access inside of my controllers without bucking iOS development best practices?
- How can I access entities from Core Data while following DRY?
- How do I pass managed objects between methods and controllers while maintaining their type?
The Core Data documentation provides some snippets for fetching records. This question is essentially asking where that logic belongs in an iOS application, and how to actually interact with the fetched records after fetching them.
An Example
This question isn't meant to be a broad, sweeping question so I will ground it in an example attempt to use Core Data. In my example I have a single UIViewController which has a label. I want this label to show the salary from a job.
import UIKit
import CoreData
class JobViewController: UIViewController {
@IBOutlet var salaryLabel: UILabel!
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
func updateLabel() {
var job = getCurrentJob()
salaryLabel.text = job.salary // ERRORS
}
func getCurrentJob()->(???) {
var error: NSError?
if let fetchedResults = managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName:"Job"), error: &error) {
return fetchedResults[0]
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
This example will not compile for two reasons:
- I didn't specify a return type for getCurrentJob, since I wasn't sure what type to return
- The line with "ERRORS", which tries to access the
salary
attribute, will error because there is no way of knowing that salary is an actual attribute of job.
How do I pass around and use the job object?