Change objectForKey value on each button click - ios

I am downloading a key from plist to my array on button click, like this:
- (IBAction)nextKey:(id)sender {
NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:#"text.plist"];
NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
wordsArray = [dict objectForKey:#"key1"];
}
I need change key value to the next from plist on each button click.
How i can do this?

Add an NSArray in your class. And keyvalue in it.Also add a int variable.Like
NSArray *arrKey = [[NSArray alloc] initWithObjects:#"Key1",#"Key2",#"Key3",#"Key4",#"Key5", nil];
int flagKey = 0;
- (IBAction)nextKey:(id)sender {
NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:#"text.plist"];
NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
wordsArray = [dict objectForKey:[arrKey objectAtIndex:flagKey]];
if(flagKey < arrKey.count-1){
flagkey++;
}
}

You can maintain a count and each time when button pressed , increase the count like
-(IBAction)nextKey:(id)sender {
NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:#"text.plist"];
NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
wordsArray = [dict objectForKey:[NSString stringWithFormat:#"key%d",index]];
index++;
}
Or you can set the button tag, and alter it every time when you press Button. Set initially it to 0 or starting key name in your plist file
-(IBAction)nextKey:(id)sender {
UIButton *button = (UIButton *)sender;
NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:#"text.plist"];
NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
wordsArray = [dict objectForKey:[NSString stringWithFormat:#"key%d",button.tag]];
button.tag = button.tag + 1;
}

Related

Write NSArray to plist file

I have a code to get the data of a plist file and a code to write data to a plist file. Now the things is, that it add's the readed data in one array (See images).
I want it in different arrays (See green image)
HERE IS MY CODE:
- (void)WriteData {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"MuziekList.plist"];
if ([fileManager fileExistsAtPath:path] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"MuziekList" ofType:#"plist"];
[fileManager copyItemAtPath:resourcePath toPath:path error:&error];
}
//_______________________________________________________________________________________________________________
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSArray *NummerTexts;
NummerTexts = [savedStock objectForKey:#"Nummers"];
NSString *NummerTextsR = [[NummerTexts valueForKey:#"description"] componentsJoinedByString:#" - "];
NSArray *ArtiestTexts;
ArtiestTexts = [savedStock objectForKey:#"Artiesten"];
NSString *ArtiestTextsR = [[ArtiestTexts valueForKey:#"description"] componentsJoinedByString:#" - "];
//_______________________________________________________________________________________________________________
NSUserDefaults *CurrentVideoNummerResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoNummer = [CurrentVideoNummerResult stringForKey:#"CurrentVideoNummer"];
NSUserDefaults *CurrentVideoArtiestResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoArtiest = [CurrentVideoArtiestResult stringForKey:#"CurrentVideoArtiest"];
/*
NSUserDefaults *CurrentVideoIDResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoID = [CurrentVideoIDResult stringForKey:#"CurrentVideoID"];
*/
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSMutableArray *newArray2 = [[NSMutableArray alloc] init];
newArray = [NSMutableArray arrayWithObjects:CurrentVideoNummer, NummerTextsR, nil];
[plist setObject:newArray forKey:#"Nummers"];
newArray2 = [NSMutableArray arrayWithObjects:CurrentVideoArtiest, ArtiestTextsR, nil];
[plist setObject:newArray2 forKey:#"Artiesten"];
[plist writeToFile:path atomically:YES];
}
Click link for images
https://www.dropbox.com/sh/wrk8h8cnwye8myx/AADl4omkGdl3S4ESXv6NbymVa?dl=0
Your question and problem are confusing. Maybe this will help:
Your code reads your current array (NummerTexts), flattens that array to a single string (NummerTextsR), gets a second string (CurrentVideoNummer), then builds a two-element array (newArray).
Your question appears to be why do you get a two-element array...?
If you don't want to flatten your original array don't do so, just make a mutable copy of it, something like:
NSMutableArray *existingTexts = [[NummerTexts valueForKey:#"description"] mutableCopy];
add your new element:
[existingTexts addObject:currentVideoNummer];
and write it back like you already are.
HTH
BTW Do not start local variable names with an uppercase letter, this goes against convention and is why the syntax highlighting in your question is all wrong.

Get object data from pList and populate in cellForIndexPath

I am trying to get the child element SHOP from a plist. The plist is as so :
Settings is a section.
I tried using the following but not sure how to put it in a cellForIndexPath
NSDictionary *region = [self.dict valueForKey:#"Settings"];
NSString *name = [region valueForKey:#"Shop"];
NSLog(#"%#", name);
My Plist is as so:
NSString *path = [[NSBundle mainBundle] pathForResource:#"PropertyList" ofType:#"plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.dict = tempDict;
NSArray *tempArray = [[NSArray alloc] init];
self.namesArray = tempArray;
self.sectionArray = [self.dict allKeys];
If what you need is to read the "Shop" array from the "item 0" dictionary you need to do the following:
NSString *path = [[NSBundle mainBundle] pathForResource:#"PropertyList" ofType:#"plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.dict = tempDict;
NSArray *settingsArray = self.dict[#"Settings"];
NSDictionary *itemDict = settingsArray[0];
NSArray *shopArray = itemDict[#"Shop"];
Of course you should check that the keys and indexes you're using are valid before indexing to avoid crashes.

read from .plist file

Got a little problem. I have a .plist file which contain next data
So i cant understand, how i need read first array, than in array read dictionary. Or maybe need rewrite file and change Root key to type dictionary, and read like this:
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:#"Data.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
self.personName = [temp objectForKey:#"Name"];
self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:#"Phones"]];
You can do it by the following code:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSArray *dataArray = [NSArray arrayWithContentsOfFile:plistPath];
This array will contain all the dictionaries, you can get them like:
NSDictionary *dict = [dataArray objectAtIndex:0];
SString *plistFile = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:plistFile];
for(NSDictionary *dictionary in array) {
NSLog(#"%#", dictionary);
}
NSDictionary *item0 = array[0];
NSString *imageName = item[0][#"name"];

Displaying plist based on variable

I am currently displaying my plist using the code below, which works, however this seems inefficient to me and I presume there is a cleaner approach.
if ([self.title isEqual: #"How to wear a Kilt"]){
NSString *path = [[NSBundle mainBundle] pathForResource:#"wearAKilt" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
thumbImg = [dict objectForKey:#"thumbImg"];
stepLabel = [dict objectForKey:#"stepLabel"];
descLabel = [dict objectForKey:#"descLabel"];
}
// Find out the path of recipes.plist
else if ([self.title isEqual: #"How to tie a cravat"]){
NSString *path = [[NSBundle mainBundle] pathForResource:#"wearACravat" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
thumbImg = [dict objectForKey:#"thumbImg"];
stepLabel = [dict objectForKey:#"stepLabel"];
descLabel = [dict objectForKey:#"descLabel"];
}
else if ([self.title isEqual: #"How to wear a sporran"]){
NSString *path = [[NSBundle mainBundle] pathForResource:#"wearASporran" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
thumbImg = [dict objectForKey:#"thumbImg"];
stepLabel = [dict objectForKey:#"stepLabel"];
descLabel = [dict objectForKey:#"descLabel"];
}
I have tried using a if statement just on the *path but this (as expected) produces a undeclared identifier path error.
if ([self.title isEqual: #"How to wear a Kilt"]){
NSString *path = [[NSBundle mainBundle] pathForResource:#"wearAKilt" ofType:#"plist"];
} else if ([self.title isEqual: #"How to tie a cravat"]) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"wearACravat" ofType:#"plist"];
}
Any suggestions?
You second bit of code, just do:
NSString *path;
if ([self.title isEqual: #"How to wear a Kilt"]){
path = [[NSBundle mainBundle] pathForResource:#"wearAKilt" ofType:#"plist"];
} else if ([self.title isEqual: #"How to tie a cravat"]) {
path = [[NSBundle mainBundle] pathForResource:#"wearACravat" ofType:#"plist"];
}
You could also use a dictionary to map from the incoming string to the associated file name...
e.g.
NSDicttionary *mapping = #{
#"How to wear a Kilt" : #"wearAKilt",
#"How to tie a cravat" : #"wearACravat",
};
Which could be a static definition, and should probably consider localisation. Then:
NSString *name = [mapping objectForKey:self.title];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:#"plist"];

Can't Read plist File

I am having trouble reading the data in a plist file. I'm not getting the titleString printed in the console like I'm expecting. What am I doing wrong?
NSString *path = [[NSBundle mainBundle] pathForResource:#"Events" ofType:#"plist"];
NSDictionary *dictPri = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
NSMutableArray *arrEvents = [[NSMutableArray alloc] initWithArray:[dictPri valueForKey:#"Root"]];
for (NSDictionary *dict in arrEvents)
{
NSString *titleString = nil;
NSString *date = nil;
titleString = [NSString stringWithFormat:#"%#",[dict valueForKey:#"Title"]];
date = [NSString stringWithFormat:#"%#",[dict valueForKey:#"Date"]];
NSLog(#"Title String: %#", titleString);
}
Your main element (Root) is Dictionary - not Array - change it in plist by clicking on type next to it.
Also there is a problem in your code - you never access "Root" element by name - it's by default top-level object. Consider taking out additional array initialization which is not required.
Fixed code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Events" ofType:#"plist"];
NSArray* arrEvents = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *dict in arrEvents)
{
NSString *titleString = [NSString stringWithFormat:#"%#",[dict objectForKey:#"Title"]];
NSString *date = [NSString stringWithFormat:#"%#",[dict objectForKey:#"Date"]];
NSLog(#"Title String: %#", titleString);
}

Resources