iOS 设备上的 .plist 路径


-(void)login{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:@"login" ofType:@"plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    [plistDict setObject:@"si" forKey:@"stato"];
    [plistDict writeToFile:path atomically: YES];
}

iOS模拟器中,plist已被正确编写,但是当我尝试在iPhone上编写.plist时,它不起作用。我想这是因为错误的 .plist 路径。iOS 设备是否使用不同的路径?

首先,您必须检查文件是否退出文档目录中。如果它没有退出那里,那么您可以将其复制到文档目录。你可以这样做

-(void)login{
    BOOL doesExist;
    NSError *error;
    NSString *filePath= [[NSBundle mainBundle] pathForResource:@"login" ofType:@"plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"login.plist"]];
    doesExist= [fileManager fileExistsAtPath:path];
    if (doesExist) {
        NSMutableDictionary* plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:path];                
    }
    else
    {    
        doesExist= [fileManager copyItemAtPath:filePath  toPath:path error:&error];
        NSMutableDictionary* plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];        
    }  
    [plistDict setObject:@"si" forKey:@"stato"];
    [plistDict writeToFile:path atomically: YES];
}

您不能写入 [NSBundle mainBundle] 位置。为了像 plist 一样写入文件,您应该保存在文档文件夹中,这样:

NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *filePathToSave = [arrayPaths objectAtIndex:0];

如果 plist 是您应用程序的一部分,我建议您在第一次启动时已经使用相同的filePathToSave将其复制到文档文件夹中,这样您就可以始终在那里查看它,无论是阅读还是保存。

这是一个很大的错误,因为主捆绑包是可读的,并且仅在编译时在应用程序捆绑包中组合。App Bundle 位于单独的位置,而应写入磁盘的数据应放置在沙盒的"文档"、"临时"或"库"文件夹中。

要获得更多理解,请阅读官方文件系统编程指南。
你需要知道的一切都写在那里。
您也可以写入子文件夹,在与iTunes或iCloud同步时,您应该在上述3个主目录之间进行备份。例如,不会备份 tmp 文件夹中的内容。

您不能写入 iOS 设备上的 mainBundle。您必须将文件保存到目录中并在那里进行修改。

只是为了将答案带入现代世界 - 您应该真正使用基于 URL 的方法来获取目录:

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSURL *URLForDocumentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]

最新更新