Saving files in cocoa

2019-02-17 18:03发布

问题:

I'm sure this is a really easy to answer question but I'm still new to cocoa. I need to save my applications data. The app has 4 text fields and each field needs to be saved into one file. Then when you open the file it needs to know what goes in what field. I'm really stuck with this. Also, I do know how to use the save panel.

回答1:

A convenient way would be to use PLists:

NSDictionary *arr = [NSDictionary dictionaryWithObjectsAndKeys:
                      string1, @"Field1", string2, @"Field2", nil];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:arr
                format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];

NSSavePanel *panel = [NSSavePanel savePanel];

NSInteger ret = [panel runModal];
if (ret == NSFileHandlingPanelOKButton) {
    [data writeToURL:[panel URL] atomically:YES];
}

For deserialization:

NSData       *data = [NSData dataWithContentsOfURL:urlOfFile];
NSDictionary *dict = [NSPropertyListSerialization propertyListFromData:data
                       mutabilityOption:NSPropertyListImmutable
                       format:nil errorDescription:nil];
NSString *string1 = [dict objectForKey:@"Field1"];
// ... etc.


标签: file cocoa save