【发布时间】:2012-02-02 12:02:22
【问题描述】:
我正在从 iPhone 应用程序调用 Web 界面以从服务器获取数据。现在我想在本地存储这些数据。在网上搜索后,我得到了可行的解决方案,将所有这些东西都存储在本地 plist 文件中,而不是存储在数据库中。
那么,我是否可以将复杂结构或具有嵌套字典的嵌套数组存储到 plist 文件中?
下面是我用来在本地存储它的代码 sn-p。使用此代码,.plist 在应用程序的文档目录中成功创建,可在模拟器中访问。
-(NSString *)Return_PlistPathCreation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *libraryPath = [paths objectAtIndex:0];
NSString *plistPath = [libraryPath stringByAppendingPathComponent:@"LoadedNews.plist"];
// Checks if the file exists at the writable location.
if ( ![[NSFileManager defaultManager] fileExistsAtPath:plistPath] ) {
NSString *masterFilePath = [[NSBundle mainBundle] pathForResource:@"LoadedNews" ofType:@"plist"];
// Try to copy the master file to the writable location
NSError *error;
if ( ![[NSFileManager defaultManager] copyItemAtPath:masterFilePath toPath:plistPath error:&error] ) {
NSLog(@"Error: %@", [error localizedDescription]);
// Serious error.
}
}
return plistPath;
}
下面的代码写入数组的数据。但是文件上没有写入任何内容。如果我使用具有多个键值对的字典,我可以将内容写入同一个 plist 文件。
//This code works perfectly.
NSArray *arr =[NSArray arrayWithObjects:@"ajay",@"sharma",nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:arr forKey:@"FullName"];
[[dict JSONRepresentation] writeToFile:plistPath atomically:YES encoding:NSASCIIStringEncoding error:nil];
但是相同的代码不适用于我的数组,它已经解析了其中的内容。
NSArray *arr =[NSArray arrayWithArray:ComplexDataArray];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:arr forKey:@"Data"];
[[dict JSONRepresentation] writeToFile:plistPath atomically:YES encoding:NSASCIIStringEncoding error:nil];
将数据写入.plist文件的问题在哪里?
【问题讨论】:
-
您是否尝试检查错误参数?它说什么?
标签: ios4 file-io iphone-sdk-3.0 plist