Database Reference
In-Depth Information
Now that you know something about beginning with a seeded database, let's start
learning about multiple managed object contexts by adding a second context with a
private queue to the Surf Journal app.
Doing work in the background
If you haven't done so already, tap the Export button at the top-left and then
immediately try to scroll the list of surf session journal entries. Notice anything?
The export operation will take several seconds and it will prevent the UI from
responding to touch events, such as scrolling.
The UI is blocked during the export operation because both the export operation
and UI are using the main queue to perform their work. This is the default
behavior.
How can you fix this? The traditional way would be to use Grand Central Dispatch to
run the export operation on a background queue. However, Core Data managed
object contexts are not thread-safe. That means you can't just dispatch to a
background queue and use the same Core Data stack.
The solution is easy: just add another context for the export operation that uses a
private queue rather than the main queue, so the export operation can do its work
in the background. This will keep the main queue free for the UI to use.
But before you jump in and fix the problem, you need to understand how the
export operation works.
Exporting data
Start by viewing how the app creates the CSV strings for the Core Data entity.
Open JournalEntry.swift and find csv() :
func csv() -> String {
let coalescedHeight = height ?? ""
let coalescedPeriod = period ?? ""
let coalescedWind = wind ?? ""
let coalescedLocation = location ?? ""
var coalescedRating: String
if let rating = rating ?. intValue {
coalescedRating = String (rating)
} else {
coalescedRating = ""
}
return " \( stringForDate ()) , \(coalescedHeight) ," +
" \(coalescedPeriod) , \(coalescedWind) ," +
" \(coalescedLocation) , \(coalescedRating) \n"
 
Search WWH ::




Custom Search