我有一个Plist,其中有许多Array。在这些数组中是我正在阅读的不同对象,但是我在编辑数组中的这些对象时却陷入困境,然后再次将数组保存回Plist文件。
我已经像这样阅读文件......
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.)
我想知道如何编辑该对象(它是一个字符串),然后将其保存回数组,然后将该数组保存回存储它的Plist文件中。
提前致谢!
P.S - 如果需要,我愿意发布更多代码或信息。
答案 0 :(得分:1)
您无法在应用程序的主程序包中保存数据,而是必须在文档目录中执行此操作:
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];
}