[For the archives, or anyone else interested in this topic]
Ken Thomases provided a shorter version, by having the NSData
instance write the file. Jean-Daniel Dupas suggested using
CFPropertyListWriteToStream to bypass the intermediate NSData object
(a speed and memory footprint improvement)
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *err = nil;
NSData *plist;
NSDictionary *dict;
char *payload = "This is the payload";
// 1 - get a XML (text) file representation
[dict writeToFile:@"/tmp/text.plist" atomically:NO];
// get a binary file representation - creates an additional
NSData in memory object
plist = [NSPropertyListSerialization dataFromPropertyList:dict
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&err];
if(plist == nil) {
NSLog(@"NSPropertyListSerialization error: %@", err);
return -1;
}
// 2 - have the NSData object save a binary representation
[plist writeToFile:@"/tmp/binary1.plist" atomically:NO];
// get a binary file representation - no additional memory footprint
// NOTE: documentation does not state it, but NSOutputStream
creates the file if it does not yet exist
NSOutputStream *str = [NSOutputStream
outputStreamToFileAtPath:@"/tmp/binary2.plist" append:NO];
if(str == nil) {
NSLog(@"cannot create output stream");
return -1;
}