UITableView cell subtitles from plist data - ios

I want to add some subtitles to my UITableView cells (where I display continents, countries, other data). Already populated my first table with continents. Now I want to add numbers of countries as subtitle in every continent cell. I added:
int numberEurope;
numberEurope = [europe count]; //this works fine
int numberAfrica;
numberAfrica = [africa count]; //this works fine
NSNumber *myNum1 = [NSNumber numberWithInt:numberEurope];
NSNumber *myNum2 = [NSNumber numberWithInt:numberAfrica];
NSArray *myArray = [NSArray arrayWithObjects: myNum1, myNum2, nil];
cell.textLabel.text = ContinentName;
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%# countries", myArray];
return cell;
But the subtitles are the same in every cell, the full array is shown: ( 2, 2) countries instead of 2 countries in the first cell and 2 countries in the second one. What am I doing wrong? The plist I use is screenshot here: Cannot Feed UITableView with .plist

You have to select proper value based on indexPath:
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%d countries", [[myArray objectAtIndex:[indexPath row]] intValue]];

Related

For Looping through Property in an Array

I'm trying to loop through my array called songs which contains a list of the user's songs from their iPod library, but to get the title, I need to do this (to get an NSString of the song titles):
[[songs objectAtIndex:i] valueForProperty:MPMediaItemPropertyTitle]
I'm trying to create an index of the tableView, but I'm stuck at this bit:
for (NSString *title = MPMediaItemPropertyTitle in songs)
{
rowTitle= [title substringToIndex:1]; //modifying the statement to its first alphabet
if ([rowTitle isEqualToString:sectionTitle]) //checking if modified statement is same as section title
{
[rowContainer addObject:title]; //adding the row contents of a particular section in array
}
}
Where I get an error
-[MPConcreteMediaItem substringToIndex:]: unrecognized selector sent to instance
On this line: rowTitle= [title substringToIndex:1];.
How do I loop through songs to get the MPMediaItemPropertyTitle and then get the first letter of the song title? I thought what I am doing is declaring the NSString 'title and looping through all the titles in songs. Clearly I'm not :S.
I'm following this tutorial. Could anybody help me out, please? Thanks.
for..in loops through the objects in the songs array. It won't send a valueForProperty message automatically, so you'll have to do that yourself:
for (MPMediaItem *song in songs)
{
NSString *title = [song valueForProperty:MPMediaItemPropertyTitle];
rowTitle= [title substringToIndex:1]; //modifying the statement to its first alphabet
if ([rowTitle isEqualToString:sectionTitle]) //checking if modified statement is same as section title
{
[rowContainer addObject:title]; //adding the row contents of a particular section in array
}
}
This...
for (NSString *title = MPMediaItemPropertyTitle in songs)
Should be...
for (MPMediaItem *song in songs) {
NSString *title = [song valueForProperty:MPMediaItemPropertyTitle];
}
Your original code was pointing your title reference at an MPConcreteMediaItem item.
Try this.
for (NSString *title in songs)
{
rowTitle= [title substringToIndex:1]; //modifying the statement to its first alphabet
if ([rowTitle isEqualToString:sectionTitle]) //checking if modified statement is same as section title
{
[rowContainer addObject:title]; //adding the row contents of a particular section in array
}
}

How to change the values of an array and then view

I want to subtract 273 from the received values of array to view the temperature in Celsius.
cell.textLabel.text = [NSString stringWithFormat:#"Kelvin: %#",[day objectAtIndex:indexPath.row]];
Here day is an array of values from which I want to substract value 273
you can do this in two ways
in your cellforRowAtIndex
cell.textLabel.text = [NSString stringWithFormat:#"Kelvin: %d",[[day objectAtIndex:indexPath.row] intValue] - 273];
where u get the response on that place
assume that yourstr=#"345";
NSString *cal = [NSString stringWithFormat:#"%d", [yourstr intValue]-273];
add to ur array
[day add object: cal];
finally u show the normally in your tableview
cell.textLabel.text = [NSString stringWithFormat:#"Kelvin: %#",[day objectAtIndex:indexPath.row]];
cell.textLabel.text = [NSString stringWithFormat:#"Kelvin: %d",[[day objectAtIndex:indexPath.row] intValue] - 273];
Give it a try

NSDictionary App Crash

Trying to read a plist and change my font color depending on the option that was selected in the following settings bundle.
The following is how I am trying to accomplish it:
NSString *path = #"/var/mobile/Library/Preferences/NCNotes.plist";
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
fontSize = [[dict objectForKey:#"slideSwitched"] floatValue];
if ([[dict objectForKey:#"noteColor"] valueForKey:#"Purple"]) {
noteView.textColor = [UIColor purpleColor];
} else {
noteView.textColor = [UIColor blackColor];
}
Any ideas why this is why my app is crashing? How do I read the values and change the color depending on what was selected?
It appears that the top level of your plist is an array, not a dictionary, because at the top it says "Item 1" where all of your content is within that. So you have a dictionary within an array. So you can change your code like this:
NSString *path = #"/var/mobile/Library/Preferences/NCNotes.plist";
NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
NSDictionary *dict = array[0];
You could also change the structure of your plist so that you have a dictionary as the root instead of an array.
Also, keys are supposed to be on the left-hand side and their values on the right-hand side, so I don't see a key "noteColor". You have a key "key" with a value "noteColor", so you'll need to make that correction. I'm also not seeing a "slideSwitched" key, though it might just be outside the bounds of your screenshot.
Also the following won't work:
[[dict objectForKey:#"noteColor"] valueForKey:#"Purple"]
Whatever you get from [dict objectForKey:#"noteColor"] isn't going to be a dictionary, so calling valueForKey: on that isn't going to give you what you want.
simply you should do this with document directory
NSString *contentPath=[[NSBundle mainBundle] pathForResource:#"PLIST_FILE_NAME" ofType:#"plist"];
NSDictionary *dictionary=[NSDictionary dictionaryWithContentsOfFile:contentPath];
write your logic after this, wait a minute , its seems like you dont have a key "noteColor" also. check your plist
Here is some example code documented up the wazoo. Hopefully it will help you understand how these plists and dictionaries work. Everything will be based on your plist file (which could definitely be improved upon, but that's up to you as I don't know your specific situation).
Your question is "How do I find color based on user selection?" I will assume you get the user selection as an int. Something like "User selected 7".
//Load your plist dictionary
NSString *path = #"/var/mobile/Library/Preferences/NCNotes.plist";
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//Get the array of validValues and the array of validTitles
NSArray *valuesArray = [dict objectForKey:#"validValues"];
NSArray *titlesArray = [dict objectForKey:#"validTitles"];
//Now get the user selected index from the validValues array
int arraySelection = -1;
for(int i = 0; i < [valuesArray count]; i++)
{
NSNumber *number = [valuesArray objectAtIndex:i];
if([number intValue] == userSelectedInput)
{
arraySelection = i;
break;
}
}
if(arraySelection == -1)
{
//Not found in array
return;
}
//Now with that index get the title of the object that the user selected
NSString *userSelectedTitle = [titlesArray objectAtIndex:arraySelection];
//Now do your checking on what the user selected based on that:
if([userSelectedTitle isEqualToString:#"Purple"])
...
You could boil this down quite a bit. Currently your validValues array is completely useless. If it were out of order or missing numbers then it would be needed, but straight counting can be achieved by the validTitles array.

Add a field to each object inside an array

I'm parsing XML data of a third party provider.
They include all the information i need for each Team, except their logo.
I have all the logos imported into my project.
Is there a way to add a logo field to each team?
This is my parse method, works perfectly
-(void) parseXML{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"apikeygoeshere"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];
NSMutableArray *items = [xml objectForKey:#"TeamLeagueStanding"];
NSString *nullentry = #""; // custom code for specific reason
NSString *nullentry2 = #""; // custom code for a specific reason
[items insertObject:nullentry atIndex:0]; // custom code for a specific reason
[items insertObject:nullentry2 atIndex:1]; // custom code for a specific reason
[self setTableData:items];
}
This is my cellForRowAtIndexPath method, as you will see my logos are being feed from an array that i have inside my code, but if the team that is in 1st place drops to 2nd, the logos won't change position
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"StandingsIdent";
StandingsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
if ([item isKindOfClass:[NSDictionary class]]) {
long row = [indexPath row];
cell.cellTeamName.text = [item objectForKey:#"Team"];;
cell.cellTeamLogo.image = [UIImage imageNamed:_teamLogos[row]];
cell.cellTeamPosition.text = _teamPosition[row];
cell.cellPlayed.text = [item objectForKey:#"Played"];
cell.cellWins.text = [item objectForKey:#"Won"];
cell.cellTies.text = [item objectForKey:#"Draw"];
cell.cellLoses.text = [item objectForKey:#"Lost"]; ;
cell.cellPoints.text = [item objectForKey:#"Points"];
cell.cellInfo.text = _infoLeague[row];
}
else {
}
}
Is it possible to somehow add these logos to each team? so when team "x" moves the logo does too.
Here is the xml data structure after being parsed:
{
Draw = 10;
"Goal_Difference" = "-17";
"Goals_Against" = 39;
"Goals_For" = 22;
Lost = 11;
NumberOfShots = 395;
Played = 25;
PlayedAtHome = 13;
PlayedAway = 12;
Points = 22;
RedCards = 5;
Team = Partick;
"Team_Id" = 561;
Won = 4;
YellowCards = 41;
}
Thanks ;)
You receive an NSDictionaryfor each team - this is an immutable object so you can't change it. But, you can create a mutable copy of it (so you will have an NSMutableDictionary).
When you do:
NSMutableArray *items = [xml objectForKey:#"TeamLeagueStanding"];
it's unlikely that you actually get a mutable array back (though you might). Again though, you can create a mutable copy if not.
Then, iterate through the teams, create a mutable copy of the dictionary, add the key/value pair that you need for the logo and then replace the original entry in the array with your updated copy.
Or, an alternate approach:
Store your logos in a different dictionary, where the keys are the team names (or unique ids) and the values are the logo image names. Then, instead of _teamLogos[row] you would use _teamLogos[[item objectForKey:#"Team"]] to get the image name.

Table Views with plists

I have a plist with the structure:
Root - Dictionary
Notes - Array
Item 0 - Dictionary
Title - String
Text - String
Date - String
I am then doing:
...
NSString *noteTitle;
NSString *noteText;
NSString *noteDate;
self.notes = [self.data objectForKey:#"Notes"];
And configure the cell like this:
cell.textLabel.text = [[self.notes objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.detailTextLabel.text = [[self.notes objectAtIndex:indexPath.row] objectForKey:#"Date"];
How do I then, in a button, add the noteTitle to the "Title" value in the plist?
[self.notes addObject:noteTitle];
When the alert is shown you need to know the index of the table you're editing so you know what index to edit when the button is tapped (row below). Then, you'll be doing something like:
[[self.notes objectAtIndex:row] setObject:noteTitle forKey:#"Title"];
If you really want to add a whole new item then you should be creating a new mutable dictionary, adding noteTitle to it and then adding that dictionary to self.notes (in which case you don't need the row).
NSDictionary *d = [[NSDictionary alloc] initWithObjectsAndKeys:noteTitle, #"Title",noteText, #"Text",noteDate, #"Date", nil];
[self.notes addObject:d];
if you want to fold 2 strings:
NSString *newString=[NSString stringWithFormat:#"%#%#",oneString,secondString];

Resources