从plist获取数据到NSMutableArray并将NSMutableArray写入同一个plist iPhone

使用这段代码,我试图从Templates.plist文件中获取数据,但是我在数组中得到了空值。

//from plist NSString *path = [[NSBundle mainBundle] pathForResource:@"Templates" ofType:@"plist"]; NSMutableArray *arry=[[NSMutableArray alloc]initWithContentsOfFile:path]; NSLog(@"arrayArray:::: %@", arry); 

这是我的plist文件:

Plist文件

另外我想知道如何添加更多的string到这个plist文件,并从这个plist中删除一个string。

首先,你不能写任何东西在你的mainBundle。 为了给你写信给plist,你需要把它复制到文档目录。 这样做是这样的:

 - (void)createEditableCopyOfIfNeeded { // First, test for existence. BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Template.plist"]; success = [fileManager fileExistsAtPath:writablePath]; if (success) return; // The writable file does not exist, so copy from the bundle to the appropriate location. NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Template.plist"]; success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error]; if (!success) NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]); } 

所以调用这个函数将检查文件目录中是否存在该文件。 如果不是,则将文件复制到文档目录。 如果文件存在,它只是返回。 接下来,您只需访问该文件即可读取和写入该文件。 要访问您只需要文档目录的path,并将您的文件名称添加为path组件。

 NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *filePath = [docDir stringByAppendingPathComponent:@"Template.plist"]; 

从plist获取数据:

 NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 

将文件写回到文档目录。

  [array writeToFile:filePath atomically: YES]; 
 -(NSMutableArray *)start1 { NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Templates.plist"]; if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]){ plistArr = [NSMutableArray arrayWithContentsOfFile: plistPath]; } else { plistArr = [[NSMutableArray alloc] init]; } return plistArr; } - (void)createNewRecordWithName:(NSMutableDictionary *)dict { plistArr=[self start1]; [plistArr addObject: dict]; //[dict release]; [self writeProductsToFile:plistArr]; } - (void)writeProductsToFile:(NSMutableArray *)array1 { NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Template.plist"]; [array1 writeToFile:plistPath atomically:YES]; } 

为了得到一个可变数组的plist,使用这个类的方法:

 NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path]; 

然后,从数组中添加/删除string。 要将arrays保存到plist,请使用:

 [array writeToFile:path atomically:YES];