iOS - Can I modify a property list file live in iPhone?
I have a property list file which gets to the bundle when I build my program. Now, I would like to be to modify it with my Mac and get it updated while my program is running. I guess bundling the file is not the correct approach, as I do not seem to have any access to the contents of the bundle after it has been built.
How should I approach? It would be nice to work at least with the iPhone simulato开发者_如何学Cr but it would be veeery nice to work with the device too.
Your application bundle is signed, so it can not be modified after it is created/signed. In order to modify the plist, you need to copy it to the Documents directory for your application first. You can then modify the copy. Here is a method that I have in one of my apps that copies a file called FavoriteUsers.plist from the bundle to the documents directory during app start up.
/* Copies the FavoritesUsers.plist file to the Documents directory
* if the file hasn't already been copied there
*/
+ (void)moveFavoritesToDocumentsDir
{
/* get the path to save the favorites */
NSString *favoritesPath = [self favoritesPath];
/* check to see if there is already a file saved at the favoritesPath
* if not, copy the default FavoriteUsers.plist to the favoritesPath
*/
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:favoritesPath])
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"FavoriteUsers" ofType:@"plist"];
NSArray *favoriteUsersArray = [NSArray arrayWithContentsOfFile:path];
[favoriteUsersArray writeToFile:favoritesPath atomically:YES];
}
}
/* Returns the string representation of the path to
* the FavoriteUsers.plist file
*/
+ (NSString *)favoritesPath
{
/* get the path for the Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
/* append the path component for the FavoriteUsers.plist */
NSString *favoritesPath = [documentsPath stringByAppendingPathComponent:@"FavoriteUsers.plist"];
return favoritesPath;
}
Sort of. You have read-only access to the bundle, so what you need to do is copy over the plist from your bundle into your app's documents folder.
The documents folder is an area of your application's sandbox where you can read and write to files. So if you copy the plist there upon the very first launch of your app, you'll be able to edit and modify it to your heart's content.
There's a tutorial somebody wrote online that basically answers your exact question, so rather than try to do my own explanation here's a much better one!
http://iphonebyradix.blogspot.com/2011/03/read-and-write-data-from-plist-file.html
精彩评论