How to edit elements in plist file - objective-c

I have a Settings.plist and I want to edit some values in this file.
My function to edit/writing is:
- (void) setParamWithName: (NSString*) Name withValue: (NSString*) Value {
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Settings.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// checking if element exists, if yes overwriting
// if element not exists adding new element
[temp writeToFile:plistPath atomically:YES];
}
This function read and write (with te same values) Settings.plist.
I do not have any idea (my knowledge about objective-c is not enough) how to add new element or edit existing element. Can anyone help mi with this issue?

I think it's easier as you think.
Once you got the path of the file read it into a NSDictionary. Make a mutable copy of that dictionary with mutableCopy and NSMutableDictionary.
Now edit that mutable dictionary as you like (add s.th., remove s.th., edit s.th. and so on).
Now that you're done you can write it back to the old path as you did with temp.
Your main problem is that you're not working with a mutable version of that dicitionary. It'd make your life much easier.

Related

Read from file.Plist Returns Null

Program that Creates multiple Plist's Paths for Different information.
But only one path is not working.
(i think "writeToFile" is the problem)
code:
-(NSString *) createPath:(NSString *)withFileName
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:withFileName];
return path;
}
Path
NSLog = /var/mobile/Applications/02CABC0A-6B5B-4097-A9D1-4336BE8230B7/Documents/MessagesDB.plist
&
-(void) messagesDbFlush
{
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[_messagesDB writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);
}
"ReturnsInfo" Array is Null :/
Anyone please help?
I once had the same error.
1) Check the name of the plist in the directory listing to match your coded one
2) Check Project settings, manually delete the pre-existing plist from the "Build Settings" > "Copy Bundle Resources", and drag drop from the list.
3) Select the plist in directory listing, check Utilities sidebar, check Identity & Type > Location as valid
4) If you deleted the app's "default" plist aka bundle identifier, add copy build phase, choose destination, choose pref folder as absolut path check "copy only when installing"
This solved my returning null.
And if all fails on the bundle identifier, you can always copy the plist to pref folder by code:
NSString *path = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
BOOL PrefsExist=[[NSFileManager defaultManager] fileExistsAtPath:path];
NSString *copyPrefsPath = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (PrefsExist == 0)
{
// Copy the plist to prefs folder (one-time event)
NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:#"com.MyCompany.MyApp" ofType:#"plist"];
[fileManager copyItemAtPath:tessdataPath toPath:path error:&error];
} else
{
// Read/Write the values from plist
}
i have stored following array with 5 objects in it, its working fine on my side, try it
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];
for(int i=0;i<5;i++)
[array addObject:#"This is Demo String, You can write your own String here"];
NSString *_fileMessagesDB = #"MessagesDB.plist";
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[array writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);

My plist is changed, how to replace the changed strings in documents directory

My plist is an array with dictionaries.
At launch, the .plist is copied from bundle to documents directory if it doesn't exist there already.
But if the plist already exists in documents directory:
each dictionary must be checked against its updated twin dictionary in the bundle to look for changes in the "District" string.
And of course, replace the string if there has been made a change.
This is the copy plist function:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self copyPlist];
return YES;
}
- (void)copyPlist {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Wine.plist"];
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Wine" ofType:#"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) {
[fileManager copyItemAtPath:bundle toPath:path error:&error];
} else {
//I need to check if the "District" value has been changed in any of the dictionaries.
}
}
Any suggestion for how this could be done, or useful tutorials/sample codes?
My guess is that I have to extract the content of the plists into NSMutableArrays: bundleArray and documentsArray. Then find the matching dictionaries in the arrays. Could be done by looking at "Name" string to be equal. Then compare the two "District" strings in the matching dictionaries and look for any changes, and replace the changed ones. But I have no idea how it should be done so any help is very useful as this is very important!
I think your Dictionary Structure is as follows:
Root as "Array"
Dictionary 1 with "District as one of the key"
Dictionary 2 with "District as one of the key"
You can check if two NSDictionary at particular indexes of Array are equal or not, which I have coded below.
NSArray *bundleArray=[[NSArray alloc] initWithContentsOfFile:#"path to .plist in bundle"];;
NSArray *documentArray=[[NSArray alloc] initWithContentsOfFile:#"path to .plist in DocumentDirectory"];
BOOL updateDictionary=NO;
for(int i=0;i<bundleArray.count;i++){
NSDictionary *bundleDic=[bundleArray objectAtIndex:i];
NSDictionary *documentDic=[documentArray objectAtIndex:i];
if(![bundleDic isEqualToDictionary:documentDic])
{
/*
*if there is any change between two dictionaries.
* i.e bundle .plist has changed so update .plist in document Directory
*/
[documentDic setValue:[bundleDic objectForKey:#"District"] forKey:#"District"];
updateDictionary=YES;
}
}
//Update Dictionary
if(updateDictionary){
[documentArray writeToFile:#"path to .plist in DocumentDirectory" atomically:YES];
}

IOS - load local file in order

I have a list of image in Document folder of app.And I want to load images in order of date created.
How can I do that ?
This code will enumerate all files in your documents directory in the order they were created:
See comments in the code to understand what is going on.
NSFileManager *fm = [NSFileManager defaultManager];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *err;
// Get all files with their creation date
NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
options:0
error:&err];
// Using file's URL as the key, store creation date as the value
NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
for (NSURL *f in files) {
NSDate *creationDate;
if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
[urlWithDate setObject:creationDate forKey:f];
}
}
// Sort the dictionary on the value, which is the creation key
for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}]) {
// Check if the file is an image. Load if it is an image, otherwise skip.
NSLog(#"%#", f);
}
I would take a look: Getting a list of files in a directory with a glob
Specifically the NSFileManager. You can look at attributes of the file. From there you can most likely do a sort using NSPredicate.

NSMutableArray always return null

My problem is when I read content of plist file in an NSMutableArray always return null
NSString *resourceDocPath = [[NSString alloc] initWithString:[[NSBundle mainBundle]bundlePath]] ;
// Create the new dictionary that will be inserted into the plist.
NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary];
[nameDictionary setValue:#"walid" forKey:#"id"];
[nameDictionary setValue:#"555 W 1st St" forKey:#"lien"];
NSString *r = [NSString stringWithFormat:#"%#/download.plist", resourceDocPath];
NSLog(#"%#",r);
// Open the plist from the filesystem.
NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:r];
NSLog(#"%#",plist);
if (plist == NULL)
{
plist = [NSMutableArray array];
}
[plist addObject:nameDictionary];
NSLog(#"%#",plist);
[plist writeToFile:r atomically:YES];
when I look in the plist file I found the data that I insert only one
can you help me please?
You're trying to access the application bundle rather than the documents directory, which can be accessed via NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Populator"];. The bundle cannot be modified, so the created array is never saved, hence why it is never loaded.
First you should not check for plist == null but check for plist == nil
Second searching for the download file should be changed into the following:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"download" withExtension:#"plist"];
NSMutableArray *plist = [NSMutableArray arrayWithContentsOfURL:url];
Third:
I do not think a file with the extension of plist will return an Array.
It will probably represent an dictionary. Try creating an NSMutableDictionary instead of an array.

can't save plist. path is not writable

I'm saving a lot of informations in a plist. This one is by standart in my mainBundle.
this is my method to load the path and the data from the plist. if the file in the "application support" folder doesn't exist, i'm copying it from the mainBundle to there.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.plistPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: self.plistPath])
{
NSString *pathInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:#"plist"];
self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:pathInBundle];
NSLog(#"plist doesnt exist");
}
else {
self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:self.plistPath];
NSLog(#"plist exist");
}
NSLog(#"plist path: %#",self.plistPath);
if i add the following lines at the end, there's only NO the answer:
if([fileManager isWritableFileAtPath:self.plistPath]) NSLog(#"YES");
else NSLog(#"NO");
after all, i tried to save with [self.plist writeToFile:self.plistPath atomically:YES];, which is also not working.
sorry for answering so late - i had a lot of other stuff to do. back to my problem: i only get the error, when i try to add a new entry to my dictionary (plist). editing is no problem. i think the problem is, how i try to add the entry. my code looks like:
NSMutableDictionary *updateDict = [[self.plist objectForKey:#"comments"]mutableCopy];
NSMutableDictionary *tmpDict = [[[NSMutableDictionary alloc]init]autorelease];
[tmpDict setObject:comment forKey:#"comment"];
[tmpDict setObject:author forKey:#"author"];
[tmpDict setObject:car forKey:#"car"];
[tmpDict setObject:part forKey:#"part"];
[tmpDict setObject:date forKey:#"date"];
[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];
[self.plist setObject:updateDict forKey:#"comments"];
if([self.plist writeToFile:self.plistPath atomically:YES]) {
return YES;
}
else {
return NO;
}
self.plist is my local copy of the file at plistPath. the structure of my plist looks like: https://img.skitch.com/20111026-tcjxp9ha4up8ggtfjy7ucgqcqe.png
hope this helps
Ok, so that's not the Documents directory and iOS doesn't have an Application Support directory created in the sandbox by default, which is why you can't write.
You can either change your method call to look-up the real documents directory:
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Or, after you get the path to the Application Support directory, you must check to see if it exists already and if not, create it.
please go through the previous post which shows the different way to copy the plist from mainBundle. Use [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; method instead.
Did you find answer? if not, you need to change this line:
[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];
to
[updateDict setObject:tmpDict forKey:[NSString stringWithFormat:#"%d",[updateDict count]+1]];
Key name is string, not object.