2012-09-02 68 views
3
-(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设备使用不同的路径吗?iOS设备上的.plist路径

+0

哪里是你的.plist文件?在_resource_文件夹中还是_Documents_文件夹?因为您只能读取_resource_文件夹的权限。 – holex

+0

我已将.plist文件添加到我的xCode项目中,因此它是我的应用程序的一部分... – Wildchild89

+0

因此它位于_resource_文件夹中。您根本没有权限在_resource_文件夹中编写任何文件,您必须使用_Document_文件夹来执行此操作,首先,您必须将.pres文件从_resources_文件夹复制到_Document_文件夹,然后您可以在_Document_文件夹中自由读取或写入文件。这是你的操场。 – holex

回答

5

首先,您必须检查文件是否在文档目录中退出。如果它不存在,则可以将其复制到文档目录。你可以这样做

-(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]; 
} 
0

您无法写入iOS设备上的mainBundle。您将不得不将文件保存到一个目录并在那里修改它。

+0

有一种方法可以指定保存我应用程序的.plist文件的目录吗? – Wildchild89

+0

看看这个链接http://stackoverflow.com/a/8378916/710793和这个链接http://stackoverflow.com/a/8030213/710793 – syclonefx

2

您无法写入[NSBundle mainBundle]位置。为了写文件,如一个plist中,您应该保存在文件夹,这样说:

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

如果plist中为您的应用程序的一部分,我会建议你,在首次发射,已经将它复制到使用相同filePathToSave的文档文件夹,因此您将始终在那里查看它,以便读取或保存。

+0

编辑了一点点的答案。如果你不知道如何复制,请告诉我。如果答案解决了您的问题,请不要忘记通过点击复选标记来接受答案。 –

0

只需把答案向现代世界 - 你真正应该使用基于URL的方法来获取目录:

NSFileManager *fileManager = [[NSFileManager alloc] init]; 

NSURL *URLForDocumentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] 
1

这是一个很大的错误,因为主束仅是可读的,仅由在App Bundle的编译时间。应用程序包位于一个单独的位置,而应写入磁盘的数据应放置在沙箱的文档,临时或库文件夹中。

为了获得更多的理解,请阅读官方File System Programming Guide
你需要知道的一切都写在那里。
您也可以写入子文件夹,在与iTunes或iCloud同步时,您应该在备份方面选择上述3个主目录。例如tmp文件夹中的内容将不会被备份。