Parse the .plist items - objective-c

When i'm trying to parse something strange happends.
I'm counting my items with
NSString *bundlePathofPlist = [[NSBundle mainBundle]pathForResource:#"Mything" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:bundlePathofPlist];
NSArray *dataFromPlist = [dict valueForKey:#"some"];
NSMutableArray *data = [NSMutableArray array];
for(int i =0;i<[dataFromPlist count];i++)
{
//NSLog(#"%#",[dataFromPlist objectAtIndex:i]);
[data addObject:[NSNumber numberWithInt:[dataFromPlist count]]];
}
[self setTableData:data];
NSLog(#"%#", tableData);
And then:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
This works great but then in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
i tried
NSString *bundlePathofPlist = [[NSBundle mainBundle]pathForResource:#"Mything" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:bundlePathofPlist];
NSArray *dataFromPlist = [dict valueForKey:#"some"];
NSLog(#"%#", dataFromPlist);
cell.Data.text = [NSString stringWithFormat:#"%#", dataFromPlist];
return cell;
But the output is:
2012-08-13 23:08:48.130 [30278:707] (
Yeah,
Trol,
LOL,
)
And in my tablecell it also displays as
(
Yeah,
Trol,
LOL,
)

So you got
( yeah, trol, lol )
...in one cell, right? Now, that's natural. If you had read NSLog's or NSString's documentation, you would have found out that the %# format specifier calls an object's description method - which, in turn, for an NSArray object, is a pretty parenthesized, comma separated list of... again, the descriptions of its objects.
What you probably want is
cell.Data.text = [dataFromPlist objectAtIndex:indexPath.row];

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];

TableView section

I have an NSArray which includes a list of keys and this array comes out of a .plist.
At this moment i write this array in a UITableView, but this is not sorted and sectionized.
I want to sort this Array and want to have Sections in this UITableView which begins with the first character of each character in this Array.
As example:
Sectionname: "A"
Celltext: "Ahorn"
I hope you get it.
My Code now:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSArray * sections = [temp allValues];
NSUInteger *tablesections = [sections count];
return tablesections;
}
And:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
NSArray * values = [temp allValues];
[EingabeListe addObjectsFromArray:values];
char szDecryptetKey[256];
sleep(0.5);
NSString *cellValue = [values objectAtIndex:indexPath.row];
const char *cString = [cellValue cStringUsingEncoding:NSASCIIStringEncoding];
DecryptKey(cString, szDecryptetKey);
NSString *pnssDecryptetKey = [NSString stringWithFormat:#"%s",szDecryptetKey];
cell.textLabel.font = [UIFont systemFontOfSize:11.0];
cell.textLabel.text = pnssDecryptetKey;
return cell;
Thanks
I probably would not leave this in a single array. I would put it into a NSDictionary where each letter of the alphabet is a bucket to for each first letter of the alphabet (and a section). Then getting the contents of a single section would be as simple as looking up the first letter you want in the dictionary.
Start by sorting your array alphabetically. This has been asked a lot of times, but here's one answer
Next, iterate over the array and add it to a dictionary based on the first letter. Each "value" in dictionary would be an array, not just a single item. So the first time you'd get to a letter (say 'g') you'd create the "g" key in the dictionary and add an NSMutable array as the value.
As a side note, I didn't add code because this sounded like a homework assignment(of course I could be wrong). While I want to help, I wouldn't want to do it for you. That said, if it's unclear or you want more help, I'd be happy to provide).
I usually use the free Sensible TableView framework for these kind of apps. You literally just throw the array to the framework and it will automatically sort and create all the sections for you. Should take you a few minutes to implement so I recommend checking it out.
Hi thanks it works pretty fine.
But i can only see the first Character of my .plist.
I think the wrong line is this one:
NSString *cellValue = [values objectAtIndex:indexPath.row];
But here is my Code:
[super viewDidLoad];
self.EingabeListe = [NSMutableArray arrayWithCapacity:20];
NSIndexPath *indexPath = 0;
alphabet = [[NSArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",
#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",#"123",nil];
datasource = [[NSMutableDictionary alloc]initWithCapacity:[alphabet count]];
int m = 1;
int n = 0;
NSArray * values = [temp allValues];
int c = [values count];
//
char szDecryptetKey[256];
sleep(0.5);
while (m != 0) {
if ( n == c){
m = 0;
}else{
NSString *cellValue = [values objectAtIndex:indexPath.row];
const char *cString = [cellValue cStringUsingEncoding:NSASCIIStringEncoding];
NSString *pnssDecryptetKey = [NSString stringWithFormat:#"%s",szDecryptetKey];
[EingabeListe addObject:pnssDecryptetKey];
pnssDecryptetKey = 0;
}
n++;
}
for(int i = 0; i<[alphabet count]; i ++)
{
NSArray *filteredArray = [EingabeListe filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF BEGINSWITH[C] %#", [alphabet objectAtIndex:i]]];
if([filteredArray count]>0)
[datasource setObject:[filteredArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)] forKey:[alphabet objectAtIndex:i]]; // Dictionary containing sorted array of data with key as alphabets
}
}
In my .plist are some Test Keys and Values like this:
Value Key
sqq hi
zzz eg
egg bb
but in my.plist i can only see:
sqq
sqq
sqq
why?
For that you need to do modification in code; I will explain.
Steps:
Initialize the alphabets array and filter use source array based on the alphabets.
Now dataSource dictionary contains array of source data filtered by alphabets.
Now number of sections will the no. of array in the dictionary.
Load the data source array for each section from the datasource dictionary.
Initialize alphabets array and datasource array:
alphabet = [[NSArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",
#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",nil];
dataSource = [[NSMutableDictionary alloc]initWithCapacity:[alphabet count]];
sourceArray = [NSArray arrayWithObjects:#"Azz",#"ax",#"aje",#"B",#"C",#"Ca",#"D",#"DD",#"E",#"EE",#"F",#"G",#"F", nil];
Filter the source array and add the data into the dictionary with key values as alphabets:
for(int i = 0; i<[alphabet count]; i ++)
{
NSArray *filteredArray = [sourceArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF BEGINSWITH[C] %#", [alphabet objectAtIndex:i]]];
if([filteredArray count]>0)
dataSource setObject:[filteredArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)] forKey:[alphabet objectAtIndex:i]]; // Dictionary containing sorted array of data with key as alphabets
}
And you need to customize the number of sections and rows delegate methods. See the sample code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [[dataSource allKeys] count];
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
{
return [[dataSource allKeys] objectAtIndex:section];
}
Entire source code:
- (void)viewDidLoad
{
[super viewDidLoad];
alphabet = [[NSArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",
#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",nil];
dataSource = [[NSMutableDictionary alloc]initWithCapacity:[alphabet count]];
sourceArray = [NSArray arrayWithObjects:#"Azz",#"ax",#"aje",#"B",#"C",#"Ca",#"D",#"DD",#"E",#"EE",#"F",#"G",#"F", nil];
for(int i = 0; i<[alphabet count]; i ++)
{
NSArray *filteredArray = [sourceArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF BEGINSWITH[C] %#", [alphabet objectAtIndex:i]]];
if([filteredArray count]>0)
[dataSource setObject:[filteredArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)] forKey:[alphabet objectAtIndex:i]]; // Dictionary containing sorted array of data with key as alphabets
}
NSLog(#"Filtered Array %#", dataSource);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [[dataSource allKeys] count];
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
{
return [[dataSource allKeys] objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[dataSource objectForKey:[[dataSource allKeys] objectAtIndex:section]] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 20;
}
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
return NO;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
originalSource = [dataSource objectForKey:[[dataSource allKeys] objectAtIndex:indexPath.section]];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:#"%#",[originalSource objectAtIndex:indexPath.row]];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
Output will be like this:

NSMutableArray works in ViewDidLoad, but not in DidSelectRowAtIndexPath

Menu.h
#interface Menu : UITableViewController {
NSMutableArray *arrayCellCollectionOrder;
NSMutableDictionary *dictCellCollection;
NSMutableDictionary *dictCellIndividual;
}
#property (nonatomic, retain) NSMutableArray *arrayCellCollectionOrder;
#end
Menu.m
ViewDidLoad works as normal.
#synthesize arrayCellCollectionOrder;
- (void)viewDidLoad {
// Codes to read in data from PLIST
// This part works
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:#"InfoTableDict.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:#"InfoTableDict" 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);
}
arrayCellCollectionOrder = [[[NSMutableArray alloc] init] retain];
arrayCellCollectionOrder = [temp objectForKey:#"CellCollectionOrder"];
// I can access `arrayCellCollectionOrder` here, it's working.
}
cellForRowAtIndexPath works as normal. I can access arrayCellCollectionOrder.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"PhotoCell";
PhotoCell *cell = (PhotoCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"PhotoCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[PhotoCell class]]) {
cell = (PhotoCell *) currentObject;
break;
}
}
}
// Copy the specific dictionary from CellCollection to Cell Individual
dictCellIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:#"%#", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]];
cell.photoCellTitle.text = [dictCellIndividual objectForKey:#"Title"]; // Load cell title
cell.photoCellImage.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#", [dictCellIndividual objectForKey:#"ThumbnailFilename"]]]; // Load cell image name
return cell;
}
didSelectRowAtIndexPath NOT WORKING. I cannot access arrayCellCollectionOrder.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Browser
NSMutableArray *arrayPhotos = [[NSMutableArray alloc] init];
NSLog(#"indexPath.row = %d", indexPath.row); // Returns the row number i touched, works.
NSLog(#"arrayCellCollectionOrder = %#", [NSString stringWithFormat:#"%#", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]); // DOES NOT WORK.
// Copy the specific dictionary from CellCollection to Cell Individual
dictCellIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:#"%#", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]]; // This similar line gives error too.
... ...
... ...
... ...
... ...
}
Error is:
* Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (1) beyond bounds (0)'
i.e.: I clicked on row 1, but arrayCellCollectionOrder is NULL.
There should have data in arrayCellCollectionOrder as it's declared in ViewDidLoad.
Is there something that I missed out?
Thanks a lot in advance.
arrayCellCollectionOrder = [[[NSMutableArray alloc] init] retain];
arrayCellCollectionOrder = [temp objectForKey:#"CellCollectionOrder"];
Do you see what you are doing to arrayCellCollectionOrder? You first assign it to a new NSMutableArray (and retain it needlessly), and then you immediately orphan the array and assign arrayCellCollectionOrder to another object that you are getting from the temp dictionary. In other words, that first line isn't doing anything for you, other than create a leaked mutable array.
If the second line is correct and you are getting a valid object and that is what you want, then the problem is that I don't see where that object is getting retained. As long as it is in the dictionary, it is probably retained, but if temp is discarded, then its members are released. If you did a
self.arrayCellCollectionOrder = [temp objectForKey:#"CellCollectionOrder"];
then the setter would retain it.

Create index for UITableView from an NSArray

I've read that the best way of creating an index (the a-z at the side of a uitableview) is to set up an array of nsdictionaries, where each dictionary corresponds to a section, and a rowValue key contains an array of the rows.
NSDictionary
headerTitle => ‘A’
rowValues => {”Aardvark”, “Ape”, “Aquaman”}
NSDictionary
headerTitle => ‘B’
rowValues => {”Bat”, “Boot”, “Bubbles”} etc
But how can this be created from an array of all the row titles - {”Aardvark”, “Ape”, “Aquaman”, ”Bat”, “Boot”, “Bubbles”, "Cat", "Cabbage" etc} ...?
I recently had a similar objective and this is how I solved it. The advantage of this over Robin's solution is that it creates the index title array dynamically based on the content of your array and it won't include indices for empty sections (plus it's a little cleaner).
I created a category of NSMutableDictionary that takes an array of data as a parameter and returns an NSMutableDictionary (we'll call it indexDictionary and it should be an instance variable):
// if your data is static, you can call this in `viewDidLoad`
indexDictionary = [NSMutableDictionary createDictionaryForSectionIndex:arrayOfStrings];
The category method:
#implementation NSMutableDictionary (DictionaryForSectionIndex)
+(NSMutableDictionary *)createDictionaryForSectionIndex:(NSArray *)array
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (char firstChar = 'a'; firstChar <= 'z'; firstChar++)
{
//NSPredicates are fast
NSString *firstCharacter = [NSString stringWithFormat:#"%c", firstChar];
NSArray *content = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF beginswith[cd] %#", firstCharacter]];
NSMutableArray *mutableContent = [NSMutableArray arrayWithArray:content];
if ([mutableContent count] > 0)
{
NSString *key = [firstCharacter uppercaseString];
[dict setObject:mutableContent forKey:key];
NSLog(#"%#: %u", key, [mutableContent count]);
}
}
return dict;
}
#end
/*
**Input:**
{"Aardvark", "Cabbage", "Boot", "Eggs", "Ape", "Aquaman", "Elephant", "Cat", "Bat", "Bubbles"}
**Output:**
NSMutableDictionary
key => 'A'
object => {"Aardvark", "Ape", "Aquaman"}
key => 'B'
object => {"Bat", "Boot", "Bubbles"}
key => 'C'
object => {"Cat", "Cabbage"}
key => 'E'
object => {"Elephant", "Eggs"}
*/
Then I create an NSArray instance variable to sort and store all the keys from indexDictionary:
// this line should follow the creation of `indexDictionary`
sortedKeys = [[indexDictionary allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
// Output, in this case, is {'A', 'B', 'C', 'E'}
You now have everything you need to set up the index for your table. Implement the following methods (if something isn't self explanatory, just let me know):
//this code assumes `sortedKeys` is not empty
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return ([sortedKeys count]);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *key = [sortedKeys objectAtIndex:section];
return [[indexDictionary valueForKey:key] count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return ([sortedKeys objectAtIndex:section]);
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return sortedKeys;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return index;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// preceding code...
NSString *key = [sortedKeys objectAtIndex:indexPath.section];
NSArray *array = [indexDictionary objectForKey:key];
NSString *yourString = [array objectAtIndex:indexPath.row];
cell.textLabel.text = yourString;
// following code...
}
The result is a table with an index that skips letters that have no associated data.
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < tableListArray.count; i++)
{
NSString *string = [tableListArray objectAtIndex:i];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:string forKey:#"Name"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
[temp2 release];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict];
[dict release];
}
[temp addObject:temp2];
detailListArray = [[NSArray alloc] initWithArray:temp];
[temp release];
[temp2 release];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
int i = 0;
for(NSArray *array in detailListArray)
{
NSString *string = [array objectAtIndex:0];
if([string compare:title] == NSOrderedSame)
break;
i++;
}
return i;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return detailListArray.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *array = [detailListArray objectAtIndex:section];
return [array objectAtIndex:0];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *titleArray = [NSMutableArray array];
[titleArray addObject:#"A"];
[titleArray addObject:#"B"];
[titleArray addObject:#"C"];
[titleArray addObject:#"D"];
[titleArray addObject:#"E"];
[titleArray addObject:#"F"];
[titleArray addObject:#"G"];
[titleArray addObject:#"H"];
[titleArray addObject:#"I"];
[titleArray addObject:#"J"];
[titleArray addObject:#"K"];
[titleArray addObject:#"L"];
[titleArray addObject:#"M"];
[titleArray addObject:#"N"];
[titleArray addObject:#"O"];
[titleArray addObject:#"P"];
[titleArray addObject:#"Q"];
[titleArray addObject:#"R"];
[titleArray addObject:#"S"];
[titleArray addObject:#"T"];
[titleArray addObject:#"U"];
[titleArray addObject:#"V"];
[titleArray addObject:#"W"];
[titleArray addObject:#"X"];
[titleArray addObject:#"Y"];
[titleArray addObject:#"Z"];
return titleArray;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *array = [detailListArray objectAtIndex:section];
return (array.count - 1);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"CELL"] autorelease];
NSArray *array = [detailListArray objectAtIndex:indexPath.section];
NSDictionary *dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *array = [detailListArray objectAtIndex:indexPath.section];
NSDictionary *dict = [array objectAtIndex:indexPath.row + 1];
int entryID = [[dict objectForKey:#"ID"] intValue];
// Do what ever you want to do with the selected row here....
}
This is the code that I have used in one of the recent projects.
I was working on one project where I need dynamic solutions for same problem so I figure out this solutions which returns dictionary with only available sections. Hope it help someone.
-(NSMutableDictionary *)getSortedDataWithArray:(NSArray *)dataArray{
NSMutableDictionary *allDataDictionary = [[NSMutableDictionary alloc]init];
for(int i = 0 ; i< dataArray.count ;i++){
NSString *currentStr = [[[dataArray objectAtIndex:i] substringToIndex:1] uppercaseString];
NSArray *allKeysArray = allDataDictionary.allKeys;
if([allKeysArray containsObject:currentStr]){
NSMutableArray *currentArray = [[NSMutableArray alloc] initWithArray:[allDataDictionary valueForKey:currentStr]];
[currentArray addObject:[dataArray objectAtIndex:i]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#" ,currentStr];
NSArray *finalArray = [currentArray filteredArrayUsingPredicate:predicate];
[allDataDictionary setValue:finalArray forKey:currentStr];
}
else{
NSMutableArray *finalArray = [[NSMutableArray alloc] initWithObjects:[dataArray objectAtIndex:i], nil];
[allDataDictionary setValue:finalArray forKey:currentStr];
}
}
return allDataDictionary;
}

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]