Mac OS X上的应用程序使用XML属性列表(或plists)存储诸如默认参数选择、应用程序设置和配置信息这样的数据。
如果你的对象是NSString、NSDictionary、NSArray、NSData或NSNumber类型,你可以使用这些类中实现的writeToFile:atomically:方法将数据写到文件中。
如果计划在程序中使用属性列表,可以查看下NSPropertyListSerialization类,使用这个类在文件中写入或读取属性列表可以在不同的平台之间移植。
示例:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDictionary *glossary = @{
@"abstract class": @"A class defined so other classes can inherit from it.",
@"adopt": @"To implement all the methods defined in a protocol",
@"archiving": @"Storing an object for later use."
};
// atomically参数被设为YES,表示希望首先将字典写入临时备份文件中,并且一旦成功,
// 将把最终数据转移到名为glossary的指定文件中。这是一种安全措施。
if ([glossary writeToFile: @"glossary" atomically: YES] == NO)
NSLog(@"Save to file failed!");
// 读取属性文件
NSDictionary *glossary1 = [NSDictionary dictionaryWithContentsOfFile: @"glossary"];
for (NSString *key in glossary1)
NSLog(@"%@: %@", key, glossary1[key]);
}
return 0;
}
运行测试 <?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"> <dict> <key>abstract class</key> <string>A class defined so other classes can inherit from it.</string> <key>adopt</key> <string>To implement all the methods defined in a protocol</string> <key>archiving</key> <string>Storing an object for later use.</string> </dict> </plist>