Database Reference
In-Depth Information
createFileAtPath(_:contents:attributes:)
to create the empty file to store the
exported data. If a file already exists at the specified file path, then the code
removes it first.
Once the app has the empty file, it can write the CSV data to disk:
// 3
var
fileHandleError:
NSError
? =
nil
let
fileHandle =
NSFileHandle
.
fileHandleForWritingToURL
(
exportFileURL, error: &fileHandleError)
if
fileHandle ==
nil
{
println
(
"ERROR:
\(fileHandleError)
"
)
}
// 4
for
object
in
results {
let
journalEntry = object
as
JournalEntry
fileHandle.
seekToEndOfFile
()
let
csvData = journalEntry.
csv
().
dataUsingEncoding
(
NSUTF8StringEncoding
, allowLossyConversion:
false
)
fileHandle.
writeData
(csvData!)
}
// 5
fileHandle.
closeFile
()
3. First, the app needs to create a file handler for writing, which is simply an object
that handles the low-level disk operations necessary for writing data. To create a
file handler for writing, the code calls
fileHandleForWritingToURL(_:error:)
.
4. Using a
for-in
statement, the code iterates over all
JournalEntry
entities. During
each iteration, the code creates a UTF8-encoded string using
csv
and
dataUsingEncoding(_:allowLossyConversion:)
. It then writes the UTF8 string to
disk using
writeData
.
5. Finally, the code closes the export file-writing file handler, since it's no longer
needed.
Once the app has written all the data to disk, it shows an alert dialog with the
exported file path: