我已经对其他有类似问题的人进行了大量研究,为他们提供的解决方案未能解决我的问题,所以我认为它缺少一些明显的东西,或者我正在验证错误和不恰当地试图识别我的错误。
我的问题是,当我尝试以编程方式保存/加载时,找不到我添加的 .plist 文件,以便为我的应用程序提供持久数据存储。
我有:
- 验证它是否列在我项目的“构建阶段”选项卡中的“复制捆绑资源”下。
- 验证该文件正在被复制到我的 /Users/Me/Library/Application Support/iPhone Simulator/5.1/Applications/Unique App ID/myapp.app 文件夹,如果删除并重新运行,它会再次出现。
- 清理并重建我的项目
我的代码被组织成保存和加载发生在两个不同的位置。当调出模态视图并且用户能够选择各种数据集时,就会发生加载。保存发生在应用程序委托- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
函数中。我已经验证了这两个函数都被调用了,尽管这种行为让我完全被难住了。
根据开发人员资源 plist 文章,相当样板的保存和加载代码:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSDictionary *someDataToSave = [NSDictionary dictionaryWithObject:self.viewController.dataStorage forKey:@"myData"];
NSString *error;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"someData.plist"];
plistPath = [rootPath stringByAppendingPathComponent:@"someData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:@"someData.plist" ofType:@"plist"];
}
NSString *generatedName = [NSString stringWithFormat:@"DataSet - %s", [NSDate date]];
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:someDataToSave forKey:generatedName];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
[plistData writeToFile:plistPath atomically:YES];
else {
NSLog(error);
}
}
-(void)loadRecordsFromPList
{
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"someData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:@"someData.plist" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp) {
NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}
self.myRecordsList = [NSMutableDictionary dictionaryWithDictionary:temp];
}
我在调试器中花了几个小时尝试各种事情,但我所做的任何调整都没有让我到任何地方。fileExistsAtPath 始终无缘无故地返回 null,尽管我在文件夹中看到了该文件,但仍找不到该文件。此外,我创建了一个仅包含一个 plist 文件的单一视图应用程序,以及一个视图控制器,其中我使用了与上面相同的 99% 的代码,并且它可以正常工作。
任何人都可以提供的任何帮助将不胜感激。在这一点上,我已经尝试了我能想到的一切,然后是一些。