Sorting keys and cellForRowAtIndexPath - objective-c

I'm new to iOS programming. I have to sort my keys in my NSDictionary or more like reverse the order of my keys.
What my current keys right now are like this;
Oh! And I do not have values for my keys as they are taken out from my XML.
NSDictionary (called GradDict);
2012 S1
2012 S2
I want it to be like this;
2012 S2
2012 S1
Here are my codes to sort it;
In parserDidEndDocument:
NSEnumerator *enumerator = [gradDict keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
NSLog(#"Key:%#",key);
NSLog(#"%#", [gradDict objectForKey:key]);
}
self.sort = [key sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
In cellForRowAtIndexPath:
ModuleCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ModuleCell"];
if (!cell)
{
cell = [[[NSBundle mainBundle] loadNibNamed:#"ModuleCell" owner:nil options:nil] objectAtIndex:0];
}
NSString *period = [self.sort objectAtIndex:indexPath.section];
NSMutableArray *periodArray = [gradDict objectForKey:period];
Module *m = [periodArray objectAtIndex:indexPath.row];
[cell.moduleNameLabel setText:[m moduleName]];
[cell.moduleCreditLabel setText:[[NSString alloc] initWithFormat:#"%d", [m moduleCredits]]];
[cell.moduleGradeLabel setText:[m moduleGrade]];
cell.contentView.backgroundColor = [UIColor colorWithRed:0.75 green:0.93 blue:1 alpha:1];
[self.tableView setSeparatorColor:[UIColor colorWithRed:0.55 green:0.55 blue:0.55 alpha:1]];
return cell;
Am I doing the sorting wrongly?
And how am I to do the cellForRowAtIndexPath?

If I understand correctly you need to sort the data in the dictionary, right?
But the dictionary sorting is not saved. You can sort the keys and then create an array.

Related

update UITableView based on array

I have JSON file who's information I put in my table. I have one button for sorting my array
I can sort my array and print it with NSLog. How can I update my table based on my sorted array?
This is my code:
-(void)sortArry:(UIButton *)sender
{
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = #[ageDescriptor];
NSArray *sortedArray = [tableData sortedArrayUsingDescriptors:sortDescriptors];
//here i have my data in nslog
NSLog(#"%# sort test",sortedArray);
}
How can I show my sortedArray in the table?
I also used
[self.tableView reloadData];
after sorting but it didn't show the sorted table
Update:
Here is my cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *objects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:nil options:nil];
for (id currentObject in objects)
{
if([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (CustomCell *) currentObject;
break;
}
}
}
id keyValuePair;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
keyValuePair = [self.filteredTableData objectAtIndex:indexPath.row];
}
else
{
keyValuePair = [self.tableData objectAtIndex:indexPath.row];
}
cell.name.text = keyValuePair[#"name"];
return cell;
}
sortedArray is deleted when it goes out of scope at the end of your sortArry: method. You need to set the property or instance variable that your UITableViewDelegate methods inspect.
Call [tableView reloadData]; after the array is sorted.
sortedArray needs to be a property of your viewController not an instance variable of sortArry , so when you reload all UITableViewdelegate method can access its values and update.
// The array You use to populate the table
#property NSArray ArrayDataSource;
Change the method signature to return the sorted array
-(NSArray *)sortArry
{
NSSortDescriptor *ageDescriptor =
[[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = #[ageDescriptor];
NSArray *sortedArray =
[tableData sortedArrayUsingDescriptors:sortDescriptors];
//here i have my data in nslog
NSLog(#"%# sort test",sortedArray);
return sortedArray;
}
Stored the return value in the datasource:
ArrayDataSource = [self.ArrayDataSource];
Finally reload the table
[self.tableView reloadData];

How to sort distance in sectional table view?

I'm making app with section tableview.The section header display district through keyArray. To row of table view, it will display all information including of name, address and distance. I can make it by below code.
Now, I'm going to sort ascending distance in tableview.
How can I sort it in 'cellForRowAtIndexPath' method?
My second thought is create NSArray at the outside of cellForRowAtIndexPath method. One is to load plist data and calculate distance. And then, sort it through NSSortDescriptor. If I go to this method, I am not sure how to populate it in section tableview correctly?
Can someone give me some idea or suggestion?
In key array, I use below code to create it in ViewDidLoad and put it into section header.
//location info draw from plist
NSArray*tempArray=[[NSArray alloc]init];
tempArray=[dataDictionary allKeys];
self.keyArray=[tempArray mutableCopy];
In cellForRowAtIndexPath, it calculate distance between target location and user location. And then display all information in table view row.
NSString*sectionHeader=[keyArray objectAtIndex:indexPath.section];
NSArray*sectionHeaderArray=[dataDictionary objectForKey:sectionHeader];
NSDictionary*targetLat=[sectionHeaderArray objectAtIndex:indexPath.row];
NSDictionary*targetLong=[sectionHeaderArray objectAtIndex:indexPath.row];
//location info draw from plist
CLLocation *targetLocation = [[CLLocation alloc] initWithLatitude:[[targetLat objectForKey:#"latitude"] floatValue] longitude:[[targetLong objectForKey:#"longitude"] floatValue]];
double distance = [self.myLocation distanceFromLocation:targetLocation]/1000;
UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier] autorelease];
}
UILabel*nameLabel=(UILabel*)[cell viewWithTag:100];
UILabel*addLabel=(UILabel*)[cell viewWithTag:101];
UILabel*latLabel1=(UILabel*)[cell viewWithTag:102];
UILabel*longLabel1=(UILabel*)[cell viewWithTag:103];
UILabel*disLabel=(UILabel*)[cell viewWithTag:106];
NSDictionary*name=[sectionHeaderArray objectAtIndex:indexPath.row];
NSDictionary*address=[sectionHeaderArray objectAtIndex:indexPath.row];
nameLabel.text=[name objectForKey:#"name"];
addrLabel.text=[address objectForKey:#"address"];
latLabel1.text=[NSString stringWithFormat:#"%f",self.myLocation.coordinate.latitude];
longLabel1.text=[NSString stringWithFormat:#"%f",self.myLocation.coordinate.longitude];
disLabel.text=[NSString stringWithFormat:#"%0.2f km",distance];
return cell;
}
I jumped to conclusions and posted an answer that was flawed. I see now that you have a multitude of issues in your process.
You assign the same object, [sectionHeaderArray objectAtIndex:indexPath.row], to several different variables and are expecting different results from each. To start with, I would make the following changes to your existing code:
NSString*sectionHeader=[keyArray objectAtIndex:indexPath.section];
NSArray *locationsForSection = [self.dataDictionary objectForKey:sectionHeader];
NSDictionary *thisLocationInfo = [locationsForSection objectAtIndex:indexPath.row];
float thisLat = [[thisLocationInfo objectForKey:#"latitude"] floatValue];
float thisLong = [[thisLocationInfo objectForKey:#"longitude"] floatValue];
//location info draw from plist
CLLocation *targetLocation = [[CLLocation alloc] initWithLatitude:thisLat longitude:thisLong];
double distance = [self.myLocation distanceFromLocation:targetLocation]/1000;
UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier];
}
UILabel*nameLabel=(UILabel*)[cell viewWithTag:100];
UILabel*addLabel=(UILabel*)[cell viewWithTag:101];
UILabel*latLabel1=(UILabel*)[cell viewWithTag:102];
UILabel*longLabel1=(UILabel*)[cell viewWithTag:103];
UILabel*disLabel=(UILabel*)[cell viewWithTag:106];
NSDictionary*name=[sectionHeaderArray objectAtIndex:indexPath.row];
NSDictionary*address=[sectionHeaderArray objectAtIndex:indexPath.row];
latLabel1.text=[NSString stringWithFormat:#"%f",thisLat];
longLabel1.text=[NSString stringWithFormat:#"%f",thisLong];
disLabel.text=[NSString stringWithFormat:#"%0.2f km",distance];
return cell;
}
For your sorting issue, I would say to go back to your dataDictionary. Iterate through each of the sectionHeader arrays. Replace each array with a copy that is sorted by the distance from myLocation. You could add the key, distance, to each dictionary there and take that out of the cellForRowAtIndexPath method entirely.
-(NSDictionary *)dataDictionary
{
if (_dataDictionary) {
return _dataDictionary;
}
NSMutableDictionary *resultDictionary = [[NSMutableDictionary alloc] init];
for (NSString *sectionHead in self.keyArray) {
NSMutableArray *sectionArrayWithDistances = [[NSMutableArray alloc] init];
NSArray *thisSectionArray = [sourceDictionary objectForKey:sectionHead];
for (NSDictionary *theLocationDict in thisSectionArray) {
// Calculate the distance
float thisLat = [[theLocationDict objectForKey:#"latitude"] floatValue];
float thisLong = [[theLocationDict objectForKey:#"longitude"] floatValue];
CLLocation *targetLocation = [[CLLocation alloc] initWithLatitude:thisLat longitude:thisLong];
double distance = [self.myLocation distanceFromLocation:targetLocation]/1000;
// Insert modified dictionary into the resulting section array
NSMutableDictionary *thisLocationWithDistance = [NSMutableDictionary dictionaryWithDictionary:theLocationDict];
[thisLocationWithDistance insertObject:[NSNumber numberWithDouble:distance] ForKey:#"distance"];
[sectionArrayWithDistances addObject:[NSDictionary dictionaryWithDictionary:thisLocationWithDistance]];
}
// Sort the resulting array for this section and insert in dataDict
NSSortDescriptor *sortByDistance = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortByDistance, nil];
[sectionArrayWithDistances sortWithDescriptors:sortDescriptors];
[resultDictionary insertObject:[NSArray arrayWithArray:sectionArrayWithDistances] forKey:sectionHead];
}
// Set result and return
self.dataDictionary = [NSDictionary dictionaryWithDictionary:resultDictionary];
return _dataDictionary;
}
Total Air Code and turned out to be more than I bargained for. Possible errors in syntax and what not but this is the basic idea as I see it for your purposes.

Checking/Unchecking a tableviewcell with sections

Previously, I had a large-ish dataset (~530 records) being displayed in a tableview. The data was held in an array of dictionaries with two keys, ID and name. Previously, I tapped a cell, it added a check mark, and it sent the cell row number to a 'selectedArray'. As I had already alphabetically sorted them (still in one section), the indexPath.row which was stored in the selectedArray corresponded to the dictionaries' array index, so I could pull data (the ID) from the record.
I decided that I would split this into headers by alphabetical order (which was an absolute pain, I don't see why it's such a complex process to insert headers into a list of records). But now, as I only used indexPath.row, when I tick the first one, it ticks the first record of each section, and only returns the number 0, so I only get the first record in the whole dataset. Is there a simple way to correct this? Really appreciate any help.
cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"inviteCell"];
// cell.accessoryType = UITableViewCellAccessoryCheckmark;
if ([checkedCells objectForKey:[NSNumber numberWithInt:indexPath.row]] != nil) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
// NSDictionary *friend = [sortedFriendsArray objectAtIndex:indexPath.row];
//---get the letter in the current section---
NSString *alphabet = [nameIndex objectAtIndex:[indexPath section]];
//---get all states beginning with the letter---
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF.name beginswith[c] %#", alphabet];
NSArray *states = [sortedFriendsArray filteredArrayUsingPredicate:predicate];
if ([states count]>0) {
//---extract the relevant state from the states object---
NSDictionary *friend = [states objectAtIndex:indexPath.row];
long long fbid = [[friend objectForKey:#"id"]longLongValue];
NSString *name = [friend objectForKey:#"name"];
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%qi/picture?type=square",fbid];
NSURL *url = [NSURL URLWithString:urlString];
UILabel *eventNameLabel = (UILabel *) [cell viewWithTag:1];
eventNameLabel.text = name;
UIImageView *eventLogo = (UIImageView*) [cell viewWithTag:2];
eventLogo.image = [UIImage imageNamed:#"112-group.png"];
// eventLogo.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];;
}
return cell;
}
CURRENT didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSNumber *indexNumber = [NSNumber numberWithInt:indexPath.row];
NSDictionary *friend = [sortedFriendsArray objectAtIndex:indexPath.row];
long long fbid = [[friend objectForKey:#"id"]longLongValue];
NSNumber *fbidNum = [NSNumber numberWithLongLong:fbid];
if ([checkedCells objectForKey:indexNumber] != nil) {
[checkedCells removeObjectForKey:indexNumber];
cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
[checkedCells setObject:fbidNum forKey:indexNumber];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
NSLog(#"Cell Pressed: %#",indexNumber);
NSLog(#"FBID: %lld",fbid);
NSLog(#"Array: %#",checkedCells);
}
It looks like you're only saving the checked cells by row, not by section and row. At minimum, don't you need to be testing the section as well as the row in this block of code?
if ([checkedCells objectForKey:[NSNumber numberWithInt:indexPath.row]] != nil) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
It's late, and I don't have my Mac handy to try this code, so maybe I'm missing something obvious. I'm not sure what you're talking about only returning zero ... is that indexPath.row?
EDIT:
To account for the section in your data array, I'd suggest storing the data as a dictionary of arrays, one dictionary entry keyed by each letter, with the inner array holding all of the entries starting with that letter. It's a little more complicated to retrieve the data, but it correctly accounts for the section.
I supposed you could create some kind of an offset to account for the number of entries in each section and then use that to index into a flat array, but that would be a lot harder to maintain, in my view. I think the dictionary of arrays is the way to go.

Application crashes when searching ONE word

I'm making my UISearchBar working and i've noticed that if i type a word, just ONE, contained in more controllers (for example "a") and i select a row, i get an unexpected crash. If i search for more than a word it works, even if contained in more than 1 controller.
i'm getting a NSRangeException:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 9 beyond bounds [0 .. 8]'
at line
cellValue = [array objectAtIndex:indexPath.row];
of my code (i have 3 sections)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//Get the nib
NSString *cellValue = nil;
if(searching)
cellValue = [copyListOfItems objectAtIndex:indexPath.row];
else {
NSDictionary *dictionary =[listaOggetti objectAtIndex:indexPath.row];
NSArray *array = [dictionary objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row];
}
NSDictionary *dict = [listaOggetti objectAtIndex:indexPath.section];
NSArray *array = [dict objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row] ; //here's the error
if (indexPath.section == 0)
{
if ([cellValue isEqual: #"FirstNib"]){
FIrstViewController *firstController = [[FirstViewController alloc] initWithNibName:#"FirstViewController" bundle:nil];
[self.navigationController pushViewController:appsController animated:YES];
[firstController release];
if ([cellValue isEqual: #"SecondNib"]){
secondViewController *secondController = [[SecondViewController alloc] initWithNibName:#"secondViewController" bundle:nil];
[self.navigationController pushViewController:secondController animated:YES];
[secondController release];
}
//and so on
}
if (indexPath.section == 1){
if ([cellValue isEqual: #"ThirdNib"]){
ThirdViewController *firstController = [[ThirdViewController alloc] initWithNibName:#"ThirdViewController" bundle:nil];
[self.navigationController pushViewController:ThirdController animated:YES];
[ThirdController release];
}
//and so on
}
if (indexPath.section == 2) {
if ([cellValue isEqual #"FourthNib"]){
FourthViewController *firstController = [[FourthViewController alloc] initWithNibName:#"FourthViewController" bundle:nil];
[self.navigationController pushViewController:FourthController animated:YES];
[FourthController release];
}
}
(the line is not the one in the IF state)
Now. I know that it goes over the array, trying to access to the 10th element.
Passing the mouse over the line "array" here
cellValue = [array objectAtIndex:indexPath.row] ;
It tells me there are 9 objects on it, while there should be 45, as i declared them here, for the key #"Elementi":
- (void)viewDidLoad {
[super viewDidLoad];
listaOggetti = [[NSMutableArray alloc] init];
NSArray *arrayDesk = [NSArray arrayWithObjects: #"First",#"Second",#"Third"..#"9th", nil];
NSArray *sortedDesk = [arrayDesk sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictDesk = [NSDictionary dictionaryWithObject:sortedDesk forKey:#"Elementi"];
NSArray *arrayLion = [NSArray arrayWithObjects:#"First1",#"Second1" ... #"30th", nil];
NSArray *sortedLion = [arrayLion sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictLion = [NSDictionary dictionaryWithObject:sortedLion forKey:#"Elementi"];
NSArray *arrayRestore = [NSArray arrayWithObjects:#"First2",#"Second2" ... #"6th", nil];
NSArray *sortedRestore = [arrayRestore sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictRest = [NSDictionary dictionaryWithObject:sortedRestore forKey:#"Elementi"];
[listaOggetti addObject:dictDesk];
[listaOggetti addObject:dictLion];
[listaOggetti addObject:dictRest];
copyListOfItems = [[NSMutableArray alloc] init];
self.navigationItem.title = NSLocalizedString(#"TIPS", #"Tips");
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"window.png"]];
//Add the search bar
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searching = NO;
letUserSelectRow = YES;
CGRect bounds = self.tableView.bounds;
bounds.origin.y = bounds.origin.y + searchBar.bounds.size.height;
self.tableView.bounds = bounds;
}
Shouldn't it see all the object for the key #"Elementi"? I'm on it from days, i can't understand how to solve, though.
Any help appreciated
*EDIT *
I noticed that
NSDictionary *dict = [listaOggetti objectAtIndex:indexPath.section];
has only 9 elements, as well as in the first array, but i have 3 dictionaries: dictDesk, dictLion, dictRest.
How can i do to select all the 45 elements in the NSDictionary?
*EDIT 2 *
Thanks to pengOne, i finally filled a global array with my 45 elements,this way
NSMutableArray *allObjects = [[NSMutableArray alloc] init];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:0] objectForKey:#"Elementi"]];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:1] objectForKey:#"Elementi"]];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:2] objectForKey:#"Elementi"]];
Now all i need to do it's to adapt something like this
NSDictionary *dictionary =[listaOggetti objectAtIndex:indexPath.row];
NSArray *array = [dictionary objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row];
to the global array i've done, so it can let me search and select contents, either from tableView and SearchView.
The error tells you that you are sending this message:
[array objectAtIndex:9];
when array has 9 object, and it only responds to
[array objectAtIndex:0];
...
[array objectAtIndex:8];
The lines you need to investigate are:
NSArray *array = [dictionary objectForKey:#"Elementi"];
selectedRow = [array objectAtIndex:indexPath.row];
Check [dictionary objectForKey:#"Elementi"]. It appears to be an NSArray with 9 objects, when it needs to be an NSArray with at least 10 objects in order to access the object at index 10.
For your viewDidLoad method, it looks to me like listaOggetti is an NSMutableArray with 3 objects: dictDesk has 9 elements, dictLion has 30 elements, and dictRest has 6 elements.
To fix this error, you will need to change the number of rows in section 0 to be 9, the number of rows in section 1 to be 30 and the number of rows in section 2 to be 6.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* cellValue=#"";
if (searching)
cellValue = [copyListOfItems objectAtIndex:indexPath.row];
else{
NSDictionary *dictionary = [listaOggetti objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row];
}
if ([cellValue isEqual: #"Apps on specific Desks"] || [cellValue isEqual: #"Applicazioni su piĆ¹ Scrivanie"]){
AppsViewController *appsController = [[AppsViewController alloc] initWithNibName:#"AppsViewController" bundle:nil];
[self.navigationController pushViewController:appsController animated:YES];
[appsController release];
}
}

NSDictionary to TableView

because i'm a newby at Stackoverflow i cannot comment someones anwser yet. (my reputation is 16..). I got a question about this anwser: How do I put this JSON data into my table view? Please help me, I'm living in a nightmare :)
Fulvio sais you have to use [eventNameList addObject:event]; and [eventNameList objectAtIndex:indexPath.row]; to store and get the event data but. addObject is an NSMutableSet method and objectAtIndex:indexPath.row is not. So i cannot use this method to get the data from the NSMutableSet.
Besides that, i can use the count methods neither.
Any Idea's ?
Assuming you have an NSDictionary, you could use the [dictionary allKeys] method to retrieve an array with all keys (lets call it keyArray for now). For the rowCount you could return the count of objects in this keyArray. To get the item that needs to be displayed in the cell you could use [dictionary objectForKey:[keyArray objectAtIndex:indexPath.row]]] to get the appropriate dictionary for the displayed cell.
In code:
// use the keyArray as a datasource ...
NSArray *keyArray = [jsonDictionary allKeys];
// ------------------------- //
// somewhere else in your code ...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [keyArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// set some cell defaults here (mainly design) ...
}
NSString *key = [keyArray objectAtIndex:indexPath.row];
NSDictionary *dictionary = [jsonDictionary objectForKey:key];
// get values from the dictionary and set the values for the displayed cell ...
return cell;
}
#Tieme: apparantly the URL you use already returns an array, you don't really need to process a dictionary (you could just use the array as the dataSource), check out the following:
SBJSON *json = [[[SBJSON alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:#"http://www.my-bjoeks.nl/competitions/fetchRoutes/25.json"];
NSString *string = [[[NSString alloc] initWithContentsOfURL:url] autorelease];
NSError *jsonError = nil;
id object = [json objectWithString:string error:&jsonError];
if (!jsonError) {
NSLog(#"%#", object);
NSLog(#"%#", [object class]); // seems an array is returned, NOT a dictionary ...
}
// if you need a mutableArray for the tableView, you can convert it.
NSMutableArray *dataArray = [NSMutableArray arrayWithArray:object]
eventNameList should be defined as an NSMutableArray, not an NSMutableSet. NSMutableArray responds to both -addObject (it puts the new object at the end of the array) and -objectAtIndex: and when you think about it, a table view is essentially an ordered list and so is an array whereas a set is not.
LUCKY:)
Assuming that you might be having nsmutablearray of nsdictionary.
In such case you can get data using:
[dictionary objectforkey:#"key"] objectAtIndex:indexpath.row]