[SOLVED] Code to convert NSDictionary to binary plist file?
[SOLVED] Code to convert NSDictionary to binary plist file?
- Subject: [SOLVED] Code to convert NSDictionary to binary plist file?
- From: David Hoerl <email@hidden>
- Date: Tue, 03 Jun 2008 21:49:29 -0400
I never did get a pointers to code to convert a NSDictionary to a
binary formatted plist, but did get pointers to look at
NSPropertyListSerialization - something I had already (mis)read a few
times.
The description for the dataFromPropertyList class method seems
confusing if you don't understand that you can create a property list
with no keys: that is, you can create one with a single compliant
object, and the key becomes "root".
So, in the unlikely event that some else someday has the same mental
block, here is actual tested code that takes a NSDictionary and
creates a binary plist file:
NSDictionary *dict;
char *payload = "This is the payload";
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Hello world", @"greeting",
[NSData dataWithBytes:payload length:strlen(payload)], @"payload",
[NSNumber numberWithInt:10], @"result",
nil ];
// get a text representation, for comparison
[dict writeToFile:@"/tmp/text.plist" atomically:NO];
NSString *err = nil;
NSData *plist;
NSFileManager *manager;
BOOL ret;
manager = [NSFileManager defaultManager];
plist = [NSPropertyListSerialization dataFromPropertyList:dict
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&err];
if(plist == nil) {
NSLog(@"NSPropertyListSerialization error: %@", err);
return -1;
}
ret = [manager createFileAtPath:@"/tmp/binary.plist"
contents:plist attributes:nil];
if(ret == NO) {
NSLog(@"Create failed");
return -1;
}
Just to prove to myself that yes, you can create a property list with
other objects like NSNumbers or raw NSData, I added these two tests:
plist = [NSPropertyListSerialization
dataFromPropertyList:[NSNumber numberWithInt:1]
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&err];
if(plist == nil) {
NSLog(@"NSPropertyListSerialization error: %@", err);
return -1;
}
ret = [manager createFileAtPath:@"/tmp/tst1.plist" contents:plist
attributes:nil];
if(ret == NO) {
NSLog(@"Create failed");
return -1;
}
plist = [NSPropertyListSerialization dataFromPropertyList:[NSData
dataWithBytes:payload length:strlen(payload)]
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&err];
if(plist == nil) {
NSLog(@"NSPropertyListSerialization error: %@", err);
return -1;
}
ret = [manager createFileAtPath:@"/tmp/tst2.plist" contents:plist
attributes:nil];
if(ret == NO) {
NSLog(@"Create failed");
return -1;
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden