使用iOS SDK在运行时创建plist?

3
我是iPhone开发的新手,想知道是否有样例Objective-C代码可以在运行时从Web服务器获取数据创建一个plist,并且我想知道数据的格式应该是什么,以便我可以轻松地在运行时创建plist。

plist是一个XML文件,你可以用任何文本编辑器查看它。 - progrmr
3个回答

9

使用NSDictionary非常简单:

#define DOCUMENTS_PATH [NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES) objectAtIndex:0]

NSDictionary *myDictionary = [self parseWebResult];

// note that myDictionary must only contain values of string, 
// int, bool, array (once again containing only the same types), 
// and other primitive types (I believe NSDates are valid too).
[myDictionary writeToFile:[DOCUMENTS_PATH stringByAppendingPathComponent:@"myDict.plist"] atomically:YES];

// reading in the dictionary
myDictionary = [NSDictionary dictionaryWithContentsOfFile:[DOCUMENTS_PATH stringByAppendingPathComponent:@"myDict.plist"]];

2

Plist(Property List)文件主要被Mac OS X用来以键/值方式存储序列化对象。有多种类型的Property List文件:ASCII、XML和二进制。因此,在您的情况下,服务器应该发送XML格式的数据。从服务器接收数据后,您可以在运行时生成plist。您可以使用以下代码将数据写入.plist文件:

- (void)writeToPlist{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"WebData.plist"];
NSArray *dataToSave = [dataToSave writeToFile:filePath atomically:YES];
}

请参考此链接以及这些服务器端的链接:链接1链接2链接3链接4。它们与iPhone中使用plist有关。

1
虽然这理论上回答了问题,但我们希望您在回答中包含链接文章的关键部分,并提供参考链接。如果未能这样做,答案可能会因链接失效而面临风险。 - Kev

1
// Get the full path of file in NSDocuments 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyData.plist"];

// Save data to file
NSArray *dataToSave = /* put data in it */;
[dataToSave writeToFile:filePath atomically:YES];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接