I have Array of the 40 item and inside that dict.Dict contain the 2 string item, i want to write the string item to 0 to 1 when user click on uibutton
<array>
<dict>
<key>quote</key>
<string>Some Quotes</string>
<key>favorite</key>
<string>0</string>
</dict>
</array>
I am applying following code but it doesn`t work for me ...
-(void) addFavorite
{
NSLog(#"Hello");
[someButton setImage:[UIImage imageNamed:#"add_favoritegold.png"] forState:UIControlStateHighlighted];
NSURL *documents = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *plistUrl = [documents URLByAppendingPathComponent:#"quotes.plist"];
NSArray *plistContents = [NSArray arrayWithContentsOfURL:plistUrl];
NSMutableDictionary *editFavorite = [plistContents objectAtIndex:1];
}
it does not change the favorite 0 to 1 and my plist is in the supporting file do i have to make any changes in property list .
-(void)btnClicked
{
[arr_Data addObject:str1];
[arr_Data addObject:str2];
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsDirectory = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Data.plist"];
// This writes the array to a plist file. If this file does not already exist, it creates a new one.
[arr_Data writeToFile:path atomically: TRUE];
}
Please refer below code for your concept
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistdocumentsDirectory = [paths objectAtIndex:0];
NsString * plistFilePath = [plistdocumentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"filename.plist"]];
NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile:plistFilePath];
[[savedStock objectAtIndex:indexForWheretoStoreData] setObject:#"your value" forKey:#"your key"];
[savedStock writeToFile:filePath atomically:YES];
use [yourArray writeToURL:yourPath atomically:YES];to store data
It's a simple 4 Step Process :
1) Select the Dictionary (you want to update the "favorite" tag).
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *yourPath = [documentsDirectory stringByAppendingPathComponent:#"yourPlist.plist"];
2) Set New Value.
[yourDict setValue:#"1" forKey:#"favorite"];
3) Insert it to the Array.
NSMutableArray *yourArray = [[NSMutableArray alloc] init];
[yourArray addObject:yourDict];
4) Write that array to yourPath.
[yourArray writeToURL:yourPath atomically:YES];
Related
I am using the method below to get an array from my plist and then increase a certain value by 1, then save it. However I log the array and the value doesn't actually go up each time.
In my plist, I have an array and in that number values, each one is set to 0. So every time I run this again it goes back to 0 it seems.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"Words.plist"];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
NSMutableArray *errors = [dict objectForKey:[NSString stringWithFormat:#"Errors%d.%d", [[stageSelectionTable indexPathForSelectedRow] section] +1, [[stageSelectionTable indexPathForSelectedRow] row] +1]];
int a = [[errors objectAtIndex:wordIndexPath] intValue];
a += 1;
NSNumber *b = [NSNumber numberWithInt:a];
[errors replaceObjectAtIndex:wordIndexPath withObject:b];
[errors writeToFile:finalPath atomically:YES];
You can only write to a file in the documents-folder. You can't write to your bundle!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Namelist.plist"];
You can use NSFilemanager to copy your Plist-File to the documents-folder.
To get the path of your file:
- (NSString *)filePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"MyFile.plist"];
return filePath;
}
To copy the file if it doesn't exist:
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[self filePath]]) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"plist"];
[fileManager copyItemAtPath:path toPath:[self filePath] error:nil];
}
Now you can write your NSDictionary to the Documents-Directory:
[dict writeToFile:[self filePath] atomically:YES];
But you really need to update the array in the dict!
You are writing the array to disk, instead of the dictionary that the array originated from:
[dict writeToFile:finalPath atomically:YES];
Also, you will need to replace the Errors%d.%d object with the updated one before saving it:
[dict setObject:errors forKey:/* your formatted key*/];
Finally, as #mavrick3 pointed out, you cannot save files to your bundle, only to your application's documents directory.
I have the following block of code:
NSMutableArray* mergedSymbolsArray = [NSMutableArray array];
for (NSDictionary* aSymbol in localSet) {
NSLog(#"Symbol:%#",[aSymbol valueForKey:#"symbol"]);
[mergedSymbolsArray addObject:aSymbol];
}
[Utils writeObjectToPList:mergedSymbolsArray];
tickers = [Utils getDataFromPList];
Here is my code to read/write to a plist:
+ (void)writeObjectToPList:(id)myData {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mobile-watchlist.plist"];
[myData writeToFile:path atomically:YES];
}
+(NSMutableArray*)getDataFromPList
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mobile-watchlist.plist"];
NSMutableArray* myArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSLog(#"READING -- PList Data Count: %d", [myArray count]);
return [[NSMutableArray alloc] initWithContentsOfFile:path];
}
For some reason mergedSymbolsArray will not write to a plist. I am not sure why?
I am able to write the following into a plist:
[tickers addObject:[NSDictionary dictionaryWithObjectsAndKeys:#"GOOG", #"symbol", #"2044", #"id", nil]];
[tickers addObject:[NSDictionary dictionaryWithObjectsAndKeys:#"AAPL", #"symbol", #"686", #"id", nil]];
[tickers addObject:[NSDictionary dictionaryWithObjectsAndKeys:#"YHOO", #"symbol", #"4177", #"id", nil]];
[Utils writeObjectToPList:tickers];
Why doesn't the first block of code write to a plist?
ADDITIONAL NOTES:
Here is an example of a dictionary the mergedSymbolsArray contains:
{
"charts_count" = 2;
"created_at" = "2010-04-12T16:37:32Z";
exchange = NASDAQ;
"followers_count" = 259;
id = 8404;
industry = "<null>";
"messages_count" = 1436;
ric = "GRPN.O";
sector = "<null>";
symbol = GRPN;
title = Groupon;
"updated_at" = "2011-09-05T04:17:56Z";
}
I am guessing the writeToFile:atomically method is failing because cannot be written?
Make sure all the objects you keep in the array are the property list objects (NSString, NSData, NSArray, or NSDictionary).
It fails because dta contains sector = "<null>" whose value is interpreted as NSNull and cannot be written to a plist.
I convert NSArray or NSDictionary to NSData before serializing. Following is a category on nsarray for serializing and deserializing. This comfortableby handles some data being nsnull
-(BOOL)writeToPlistFile:(NSString*)filename{
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:self];
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
BOOL didWriteSuccessfull = [data writeToFile:path atomically:YES];
return didWriteSuccessfull;
}
+(NSArray*)readFromPlistFile:(NSString*)filename{
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
NSData * data = [NSData dataWithContentsOfFile:path];
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
Check the return value of [myData writeToFile:path atomically:YES]; please. If it's NO, some errors have occurred while writing.Try to alloc-init the NSMutableArray instead of creating an autoreleased one.
Try adding a forward slash to your file name Ie:
NSString *path = [documentsDirectory stringByAppendingString:#"/mobile-watchlist.plist"];
I have an MSMutableArray that contains many NSDictionaries. A dictionary is just an NSString with a key "symbol".
I am writing my array to a plist:
+ (void)writeObjectToPList:(id)myData {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mobile-watchlist.plist"];
[myData writeToFile:path atomically:YES];
}
How can I read this back as an array?
You can read the file back like this --
NSArray *array = [NSArray arrayWithContentsOfFile:path];
I've established how to read a BOOL from a plist, but I don't know how to write over the BOOL value I originally read.
The BOOL I'm reading is buried within my plist. When the view loads I take a dictionary from the plist that contains all the info for the view (detail view at the end of a drill down), and the BOOL is inside that dictionary. I can change the value of the BOOL in the dictionary once it's been brought into the app, but I don't know how to write this back to the postion within the plist.
Hopefully this is making sense?
Cheers!
Write a NSDictionary to a Property List:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"FileName.plist"];
NSDictionary *myDict = [[NSDictionary alloc] init];
[myDict setObject:[NSNumber numberWithBool:YES] forKey:#"myKey"];
[myDict writeToFile:filePath atomically:YES];
Read the Boolean:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"FileName.plist"];
NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
BOOL myBool = [[myDict objectForKey:#"myKey"] boolValue];
You can also put the filePath code into this function:
- (NSString *)getFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"FileName.plist"];
return filePath;
}
And use it like this: (for reading)
NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:[self getFilePath]];
BOOL myBool = [[myDict objectForKey#"myKey"] boolValue];
And this: (for writing)
NSDictionary *myDict = [[NSDictionary alloc] init];
[myDict setObject:[NSNumber numberWithBool:YES] forKey:#"myKey"];
[myDict writeToFile:[self getFilePath] atomically:YES];
For writing BOOL to .plist use below code
NSMutableDictionary* myDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[myDict setObject:[NSNumber numberWithBool:YES] forKey:#"LSUIElement"];
[myDict writeToFile:plistPath atomically:NO];
Also have look at the post
Try this function:
-(void) setStringToPropertyList:(NSString*) pList withKey:(NSString*)key andValue:(NSString*)val{
//the path.
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:pList];
//read the dictionary.
NSMutableDictionary *temp = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//modify the desired key of the dictionary.
[temp setValue:val forKey:key];
//rewrite the diccionary again.
if([temp writeToFile: plistPath atomically:YES]){
NSLog(#"setStringToPropertyList: pList updated");
}else{
NSLog(#"setStringToPropertyList: error writing the file");
}
//memory management
if(!temp) [temp release];
}
This function allows you to write properties to a pList, parameteres:
pList = name of the file
key = key of the property
val = value of the property
Hope it helps.
How to use NSMutable Dictionary in another class for read and write data from plist file in iphone....
Any Ideas?
As you can find in in NSDictionary reference, this class has a method to create a nsdictionary from a file initWithContentsOfFile:(NSString *)path . You can do something like:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"myDictionary" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
Where myDictionary is your plist name (In case of your plist is inside resource bundle).
You can write a plist on disk with the method:
[dict writeToFile:filePath atomically: YES];
Where filePath is your destination path.
See the Plist files example on this tutorial.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:plistName ofType:#"plist"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath
stringByAppendingPathComponent:#"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
myKey = (int)[[plist valueForKey:#"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:#"myKey2"] boolValue];
[plist setValue:myKey forKey:#"myKey"];
[plist writeToFile:path atomically:YES];