问题
I wrote a little sample bit of code to document how to encode Swift objects as property lists, using PropertyListEncoder
.
The code works, but I wanted to output to a binary property list. (Those are faster and more compact)
However, it seems the PropertyListEncoder is ignoring my setting outputFormat = .binary
and writing the file as XML anyway:
Here is the code (a MacOS command line tool, just because that's a low-overhead way to write some test code: )
import Foundation
var array = ["one", "two", "three"]
let plistEncoder = PropertyListEncoder()
plistEncoder.outputFormat = .binary
if let data = try? plistEncoder.encode(array)
{
let url = URL(fileURLWithPath:"array.plist")
do {
try data.write(to: url)
} catch {
print("Error writing file. Error = \(error)" )
}
}
If you open the resulting file in BBEdit, here's what you see:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>one</string>
<string>two</string>
<string>three</string>
</array>
</plist>
That is clearly XML format. What am I missing?
回答1:
Print data
and you see it's clearly binary format, starting with bplist00
<62706c69 73743030 a3010203 536f6e65 5374776f 55746872 6565080c 10140000 00000000 01010000 00000000 00040000 00000000 00000000 00000000 001a>
来源:https://stackoverflow.com/questions/61895404/propertylistencoder-is-ignoring-binary-outputformat