使用Cocoa保存XML格式记录文件是本文要介绍的内容,在Cocoa中保存XML的属性列表文件(plist)是很容易的事情。NSArray,NSDictionary, NSString, 或者 NSData都可以保存为XML格式的plist文件。如果NSArray或者NSDictionary中还包含其他可以保存为属性列表的对象,它们可以一起存储在plist文件中。
下面是保存的方法:
- @interface ClientDisplayMgr {
- …
- IBOutlet id m_clientName; // outlets to text boxes in the preferences
- IBOutlet id m_serverName; // window.
- NSArray *m_availableFriends;
- …
- }
- @end
- //
- // Save some various preferences
- - writePrefs
- {
- NSMutableDictionary * prefs;
- // allocate an NSMutableDictionary to hold our preference data
- prefs = [[NSMutableDictionary alloc] init];
- // our preference data is our client name, hostname, and buddy list
- [prefs setObject:[m_clientName stringValue] forKey:@"Client"];
- [prefs setObject:[m_serverName stringValue] forKey:@"Server"];
- [prefs setObject:m_friends forKey:@"Friends"];
- // save our buddy list to the user's home directory/Library/Preferences.
- [prefs writeToFile:[@"~/Library/Preferences/MiniMessage Client.plist"
- stringByExpandingTildeInPath] atomically: TRUE];
- return self;
- }
保存下来的结果看起来是这样的:
- < ?xml version="1.0" encoding="UTF-8"?>
- < !DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
- <plist version="0.9">
- <dict>
- <key>Client</key>
- <string>Crazy Joe</string>
- <key>Friends</key>
- <array>
- <string>Crazy Joe</string>
- <string>Jim</string>
- <string>Joe</string>
- <string>Crazy Jim</string>
- <string>Jose</string>
- <string>Crazy Joe</string >
- </array>
- <key>Server</key>
- <string>localhost</string>
- </dict>
- </plist>
要想把保存的列表文件读取出来也很简单:
- - awakeFromNib
- {
- NSString *clientName, *serverName;
- NSDictionary *prefs;
- // load the preferences dictionary
- prefs = [NSDictionary dictionaryWithContentsOfFile:
- [@"~/Library/Preferences/MiniMessage Client.plist"
- stringByExpandingTildeInPath]];
- // if the file was there, we got all the information we need.
- // (note that it's probably a good idea to individually verify objects
- // we pull out of the dictionary, but this is example code
- if (prefs) {
- //
- // write our loaded names into the preference dialog's text boxes.
- [m_clientName setStringValue: [prefs objectForKey:@"Client"]];
- [m_serverName setStringValue: [prefs objectForKey:@"Server"]];
- //
- // load our friend list.
- m_friends = [[prefs objectForKey:@"Friends"] retain];
- } else {
- //
- // no property list. The nib file's got defaults for the
- // preference dialog box, but we still need a list of friends.
- m_friends = [[NSMutableArray alloc] init];
- // we're our only friend (isn't it strange talking about we in the singular?)
- [m_friends addObject: [m_clientName stringValue]];
- }
- //
- // get our preference data for the rest of awakeFromNib
- clientName = [m_clientName stringValue];
- serverName = [m_serverName stringValue];
- …
小结:使用Cocoa保存XML格式记录文件的内容介绍完了,希望本文对你有所帮助!