Database Reference
In-Depth Information
}
As you can see, this
JournalEntry
function returns a comma-separated string of the
entity's attributes. Because the
JournalEntry
attributes are allowed to be
nil
, the
function uses the
nil
coalescing operator (
??
) so that it exports an empty string
instead of an unhelpful debug message that the attribute is
nil
.
Note:
The
nil
coalescing operator (
??
) unwraps an optional if it contains a
value; otherwise it returns a default value. For example, the following:
let coalescedHeight = height != nil ? height! : ""
Can be shortened by using the
nil
coalescing operator:
let coalescedHeight = height ?? ""
Now that you know how the app creates the CSV strings for an individual journal
entry, take a look at how the app saves the CSV file to disk. Switch to
JournalListViewController.swift
and find the following code in
exportCSVFile
:
// 1
var
fetchRequestError:
NSError
? =
nil
let
results =
coreDataStack
.
context
.
executeFetchRequest
(
self
.
surfJournalFetchRequest
(),
error: &fetchRequestError)
if
results ==
nil
{
println
(
"ERROR:
\(fetchRequestError)
"
)
}
// 2
let
exportFilePath =
NSTemporaryDirectory
() +
"export.csv"
let
exportFileURL =
NSURL
(fileURLWithPath: exportFilePath)
NSFileManager
.
defaultManager
().
createFileAtPath
(
exportFilePath, contents:
NSData
(), attributes:
nil
)
Let's go through the CSV export code step by step:
1. First, the code retrieves all
JournalEntry
entities by executing a fetch request.
The fetch request is the same one used by the fetched results controller and
therefore the code uses
surfJournalFetchRequest
to create it, avoiding
duplication.
2. The code creates the URL for the exported CSV file by appending the file name
(“export.csv”) to the output of
NSTemporaryDirectory
. The path returned by
NSTemporaryDirectory
is a unique directory for temporary file storage. This a
good place for files that can easily be generated again and don't need to be
backed up by iTunes or to iCloud. After creating the export URL, the code calls