Saving files in cocoa

前端 未结 1 496
栀梦
栀梦 2021-01-13 12:08

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 sav

1条回答
  •  不知归路
    2021-01-13 12:43

    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.
    

    0 讨论(0)
提交回复
热议问题