杀死应用程序后,属性列表数据是否仍然存在?

时间:2017-03-23 10:58:21

标签: ios objective-c iphone xcode plist

我创建了一个自定义属性列表文件。该文件存储在应用程序文档中。 用户登录成功后,登录信息存储在plist中,并且工作正常。 注销时清除plist内容,这也可以正常工作。 当我还在登录时,我杀死了该应用程序。当应用程序打开我清除的plist数据时。

用于保存到文件的代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"xxxxPlist.plist"];

if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
    plistPath = [[NSBundle mainBundle] pathForResource:@"xxxxPlist" ofType:@"plist"];
}
dict=[[self cleanDictionary:[dict mutableCopy]] mutableCopy];

NSDictionary *plistDict=[[NSDictionary alloc] initWithObjectsAndKeys:dict,@"login_data", nil];
NSError *error = nil;

NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&error];


if(plistData)
{
    [plistData writeToFile:plistPath atomically:YES];
}
else
{
    //error here
    NSLog(@"%@ ",error);
}

用于获取数据的代码

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"xxxx.plist"];

if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
    plistPath = [[NSBundle mainBundle] pathForResource:@"xxxxPlist" ofType:@"plist"];
}

NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
return [dict objectForKey:@"login_data"];

我有什么方法可以保留数据吗?

1 个答案:

答案 0 :(得分:0)

有几件事可能会导致问题

保存到文件

1)我的理解是您特别想要专门保存到/ Documents文件夹以确保文件持续

2)所以你正确构建了以下路径

"/Documents/xxxxPlist.plist"

3)但是,为什么要检查该位置是否已存在文件?

if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
    plistPath = [[NSBundle mainBundle] pathForResource:@"xxxxPlist" ofType:@"plist"];
}

准备好后,您只需要写入路径即可。 如果此位置有旧文件,则会被覆盖。 而我的理解是这是想要的行为,因为你已经读过那个文件并且数据在那个词典中“dict”。

4)另外,要求NSBundle为您提供文件名路径

"xxxxPlist.plist"

如果这样的文件碰巧存在,它有可能只返回一些名为相同文件的其他路径(不在/ Documents中)。例如,如果您之前写的是/ Cache文件夹(使用不同的代码),您的应用程序将继续获取/ Cache路径并继续读/写(不在/ Documents中)。使用现有的代码,你在第一次运行时就没有路径,所以不知道他的文件是如何创建的。

5)然后我不确定这条线到底是什么

dict=[[self cleanDictionary:[dict mutableCopy]] mutableCopy];

为什么首先制作一个可变副本,然后可能会得到不可变的副本并获得一个可变的副本。不能-cleanDictionary:只返回它传递的相同的可变副本?

从文件中读取时

1)不确定为什么要先搜索其他文件?

"/Documents/xxxx.plist" not "/Documents/xxxxPlist.plist"

如果“xxxx.plist”存在会发生什么,那么你永远不会得到你在另一部分写的“xxxxPlist.plist”。

2)然后,是的,在尝试阅读之前,您必须检查某个文件是否存在于某个路径中。但是,在你的情况下,如果它不存在,你不要求NSBundle到另一个位置,因为你需要/ Documents中的特定文件,而你不知道从NSBundle得到什么,如果你的文件是不应该在哪里。 因此,如果没有“xxxxPlist.plist”文件,那只是您第一次运行该应用程序,您将创建初始字典。