简体   繁体   English

iPhone Dev-从Plist编辑数组中的对象

[英]iPhone Dev - Edit objects in Array from Plist

I have a Plist in which I have a number of Array's. 我有一个Plist,其中有多个Array。 Within these arrays are different objects that I'm reading, I've become stuck however on editing these objects in the array and then saving the array back to the Plist file again. 在这些数组中,我正在读取不同的对象,但是在编辑数组中的这些对象然后将数组再次保存回Plist文件时,我陷入了困境。

I'm already reading the file like so... 我已经像这样读取文件了...

Array = [myArrays objectAtIndex:arrayCounter]; //This tells it which Array to load.

myObject = [Array objectAtIndex:0]; //This reads that object in the array. (This is what I want to edit.)

I was wondering how I would go about editing that object (it's a string) and then saving it back into the array and then saving that array back into the Plist file where it is stored. 我想知道如何编辑该对象(它是一个字符串),然后将其保存回数组,然后将该数组保存回存储它的Plist文件中。

Thanks in advance! 提前致谢!

PS - I'm willing to post more code or information if required. PS-如果需要,我愿意发布更多代码或信息。

You cannot save data in application's main bundle instead you have to do in document directory like this: 您不能将数据保存在应用程序的主捆绑包中,而必须在文档目录中进行如下操作:

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"];

if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath]) 
{//plist already exits in doc dir so save content in it

 NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:plistFilePath];
 NSArray *arrValue = [data objectAtIndex:arrayCounter];

 NSString *strValue = [arrValue objectAtIndex:0];
 strValue = [strValue stringByAppending:@"hello"]; //change your value here

 [[data objectAtIndex:arrayCounter] replaceObjectAtIndex:0 withObject:strValue]; //value replaced
 [data writeToFile:plistFilePath atomically:YES];
}
else{ //firstly take content from plist and then write file document directory. it will be executed only once

 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
 NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:plistPath];
 NSArray *arrValue = [data objectAtIndex:arrayCounter];

 NSString *strValue = [arrValue objectAtIndex:0];
 strValue = [strValue stringByAppending:@"hello"]; //change your value here

 [[data objectAtIndex:arrayCounter] replaceObjectAtIndex:0 withObject:strValue]; //value replaced
 [data writeToFile:plistFilePath atomically:YES];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM