简体   繁体   中英

iPhone Dev - Edit objects in Array from Plist

I have a Plist in which I have a number of Array's. 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.

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.

Thanks in advance!

PS - I'm willing to post more code or information if required.

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];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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