Dynamic arrays as section headers - iphone

I have a main array, that contains a whole bunch of dictionaries, what I want to do is to have all those dictionaries sorted according to their assigned tag. This is how a dictionary might look:
date = "2012-12-04 20:26:04 +0000";
name = H;
tag = "#J";
Heres how the main array looks:
MAIN_ARRAY
- dict1
- dict2
- dict3
I want to sort the main array like this:
MAIN_ARRAY
- tag1
- dict1
- dict2
- tag2
- dict3
Heres my code:
-(NSArray *)returnTagContent {
NSArray *tags = [all valueForKey:#"tag"];
NSMutableArray *adoptTags = [[[NSMutableArray alloc] init] autorelease];
for (NSString *tagQuery in tags) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"tag CONTAINS[cd] %#", tagQuery];
NSArray *roughArray = [all filteredArrayUsingPredicate:predicate];
NSArray *tagContent = [[NSSet setWithArray:roughArray] allObjects];
[adoptTags addObject:tagContent];
}
return adoptTags;
}
It returns the array, but now I want to organize it into section headers. How should I go about this?
I also have another piece of code with problem for returning the section header titles:
-(NSString *)returnTitleForTags {
NSString *uniqueTag = nil;
for (NSArray *tagContent in allTags) {
uniqueTag = [[[tagContent valueForKey:#"tag"] allObjects] lastObject];
}
return uniqueTag;
}
Problem? Well, I know it's because of lastObject but any other ideas to retrieve a NSString object of the array.
UPDATE: New code changes.
I update the array to display the sections when clicked by a button so like this:
isTagFilterOn=YES;
[self loadSectionsArray];
[self.tableView reloadData];
Heres the code for cellForRowAtIndexPath:
if (isTagFilterOn==YES) {
NSDictionary *dict = [[sectionsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"name"];
cell.detailTextLabel.text = [dict valueForKey:#"date"];
}
else {
NSString *object = all[indexPath.row];
cell.textLabel.text = [object valueForKey:#"name"];
cell.detailTextLabel.text = [object valueForKey:#"tag"];
}
The rest
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (isTagFilterOn==YES) {
return [sectionsArray count];
}
else {
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isTagFilterOn==YES) {
return [[sectionsArray objectAtIndex:section] count];
}
return all.count;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (isTagFilterOn==YES) {
NSDictionary *dict = [[sectionsArray objectAtIndex:section] objectAtIndex:0];
return [dict objectForKey:#"tag"];
}
return nil;
}

I think your task becomes easier if you remove duplicate "tags" before you create the array for the table view data source:
// All tags:
NSArray *tags = [mainArray valueForKey:#"tag"];
// Remove duplicates and sort:
tags = [[[NSSet setWithArray:tags] allObjects] sortedArrayUsingSelector:#selector(compare:)];
// Build an "array of arrays (of dictionaries)" as data source:
sectionsArray = [NSMutableArray array];
for (NSString *tag in tags) {
NSPredicate *pred = [NSPredicate predicateWithFormat:#"tag == %#", tag];
NSArray *onesection = [mainArray filteredArrayUsingPredicate:pred];
[sectionsArray addObject:onesection];
}
For example, if the mainArray is
(
{ date = "2012-12-04 20:26:04 +0000"; name = H; tag = "#J"; },
{ date = "2013-12-04 20:26:04 +0000"; name = X; tag = "#J"; },
{ date = "2014-12-04 20:26:04 +0000"; name = Z; tag = "#L"; }
)
then sectionsArray will be
(
(
{ date = "2012-12-04 20:26:04 +0000"; name = H; tag = "#J"; },
{ date = "2013-12-04 20:26:04 +0000"; name = X; tag = "#J"; }
),
(
{ date = "2014-12-04 20:26:04 +0000"; name = Z; tag = "#L"; }
)
)
and you can easily access each section and each row within a section:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [sectionsArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[sectionsArray objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = ...;
}
NSDictionary *dict = [[sectionsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = [dict objectForKey:#"name"];
cell.detailTextLabel.text = [dict objectForKey:#"date"];
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSDictionary *dict = [[sectionsArray objectAtIndex:section] objectAtIndex:0];
return [dict objectForKey:#"tag"];
}

Related

Want to display the array values in the table

Table View:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
tableView.delegate = self;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
[self.myTableView reloadData];
return cell;
}
I want to store the detail (array value) in the tableView.I used both method numberOfRowsInSection and cellForRowAtIndexPath but the table display null. How can I display?
Make property for NSMutable array in .h
#property (nonatomic,retain) NSMutableArray *detailArray;
and synthesize it in .m
#synthesize detailArray=_detailArray;
and change this line
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
to
_detailArray=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
then use _detailArray for displaying table data.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [_detailArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// _detailArray objects for date population.
}
Your Code :
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
arr = [parsedJson objectForKey:#"routes"];
dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
}
}
}
}
});
first you go to your .h file -->
#property (nonatomic, strong) NSMutableArray * detailsArray;
In .m file -->
#synthesize detailsArray;
replace this code
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
by this -->
self.detailsArray = [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"];
# using table datasource methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.detailsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text = [self.detailsArray objectAtIndex: indexPath.row ];
return cell;
}
}
//Note Please set the delegate method of table , if you write the code programmatically means tableView.delgate = self;
Use this :
self.detaisArray = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
NSArray *legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detaisArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
if(i == legs.count-1){
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
}
}
}
}
});
first checked you connect your tableview delegate set self...
second checked youn row count pr detailarray cont in numberOfRowsInSection its may b zero
1st Declare Your Array in .h
like this
#property(strong,nonatomic)NSMutableArray * name;
And intialize into .m Init() method
name=[NSMutableArray alloc]initWithObjects:#"a",#"b", nil];
// TableView Delegate Method To Display Array Data into Tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return name.count; //Give Your Array Name Here.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Try this code.

UISearchView not displaying search values

In my TableView which Expands on the clicking on the sections.now I am using Uisearchbar to search the sections in the table...It gives me the UIsearchbar but Search cannot be taken...
I think problem is in the numberOfRowsInSection.please check where I am getting wrong..
why searchbar is not working
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.mySections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = 0;
if ([self tableView:tableView canCollapseSection:section] || (tableView == self.searchDisplayController.searchResultsTableView) )
{
if ([expandedSections containsIndex:section] )
{
NSString *key = [self.mySections objectAtIndex:section];
NSArray *dataInSection = [[self.myData objectForKey:key] objectAtIndex:0];
return [dataInSection count];
}
return 1;
} else{
rows = [self.searchResults count];
return rows;
}
return 1;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
NSString *key = [self.mySections objectAtIndex:section];
return [NSString stringWithFormat:#"%#", key];
}
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
self.searchResults = [self.allItems filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
UISearchBar * searchBar = [controller searchBar];
[self filterContentForSearchText:searchString scope:[[searchBar scopeButtonTitles] objectAtIndex:[searchBar selectedScopeButtonIndex]]];
return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
UISearchBar * searchBar = [controller searchBar];
[self filterContentForSearchText:[searchBar text] scope:[[searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
}
// Configure the cell...
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}else {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [self.mySections objectAtIndex:section];
NSDictionary *dataForSection = [[self.myData objectForKey:key] objectAtIndex:0];
NSArray *array=dataForSection.allKeys;
cell.textLabel.text = [[dataForSection allKeys] objectAtIndex:row];
cell.detailTextLabel.text=[dataForSection valueForKey:[array objectAtIndex:indexPath.row]];
}
return cell;
}
You are not reloading your table after searching
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
self.mySections = [self.mySections filteredArrayUsingPredicate:resultPredicate];
[myTableView reloadData];
}
Edit
Your are not setting detail text label
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView])
{
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[dataForSection valueForKey:[self.searchResults objectAtIndex:indexPath.row]];
}
and after searching you are getting title now row because in your code
rows = [self.searchResults count];
return rows;
its always returning zero value. So just do it return 1;
And do other thing as your requirement,
And i will suggest you to not to use different different code for before table search and after searching.. Like if ([tableView isEqual:self.searchDisplayController.searchResultsTableView])
just use same code for both..and make changes only in array and dictionary..
initially
tableAry = globalAry;
And after searching
tableAry = searchedAry;

Sectioned UITable & JSON

I have been trying for days to figure out how to parse this JSON to a sectioned UITable but I am not successful, I've only been able to figure out how to get the section name, but failed to get each section row count and data for each row in each section.
Since the transportation group may vary from time to time and their name may change, so I guess I need to use allKeys to find out each section title 1st.
Please help and points me to the right direction to extract the data for a sectioned UITable, Thank you.
{
"transport" : {
"public" : [
{
"transport_id" : "2",
"transport_name" : "Ferry"
},
{
"transport_id" : "3",
"transport_name" : "Bus"
},
{
"transport_id" : "4",
"transport_name" : "Taxi"
},
{
"transport_id" : "5",
"transport_name" : "Tram"
}
],
"Private" : [
{
"transport_id" : "11",
"transport_name" : "Bicycle"
},
{
"transport_id" : "12",
"transport_name" : "Private Car"
}
],
"Misc" : [
{
"transport_id" : "6",
"transport_name" : "By Foot"
},
{
"transport_id" : "7",
"transport_name" : "Helicopter"
},
{
"transport_id" : "8",
"transport_name" : "Yatch"
}
]
}
}
NSDictionary *results = [jsonString JSONValue];
NSDictionary *all = [results objectForKey:#"transport"];
NSArray *allKeys = [all allKeys];
NSArray *transports = [results objectForKey:#"transport"];
for (NSDictionary *transport in transports)
{
[transportSectionTitle addObject:(transport)];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [transportSectionTitle count];
}
The easiest solution to explain is to use the all dictionary as your datasource.
NSDictionary *results = [jsonString JSONValue];
NSDictionary *all = [results objectForKey:#"transport"];
// self.datasource would be a NSDictionary retained property
self.datasource = all;
Then to get the number of sections you could do :
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.datasource count]; // You can use count on a NSDictionary
}
To get the title of the sections:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *title = [[self.datasource allKeys] objectAtIndex:section];
return title;
}
To get the number of rows in each section:
- (NSInteger)tableView:(UITableView *)favTableView numberOfRowsInSection:(NSInteger)section {
// Get the all the transports
NSArray *allTransports = [self.datasource allValues];
// Get the array of transports for the wanted section
NSArray *sectionTransports = [allTransports objectAtIndex:section];
return [sectionTransports count];
}
Then to get the rows :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Get the all the transports
NSArray *allTransports = [self.datasource allValues];
// Get the array of transports for the wanted section
NSArray *sectionTransports = [allTransports objectAtIndex:indexPath.section];
// Then get the transport for the row
NSDictionary *transport = [sectionTransports objectAtIndex:indexPath.row];
// Now you can get the name and id of the transport
NSString *tansportName = [transport objectForKey:#"transport_name"];
NSString *transportId = [transport objectForKey:#"transport_id"];
NSString *transportDescription = [NSString stringWithFormat:#"%# - %#",transportId, transportName];
cell.textLabel.text = transportDescription;
return cell;
}
That's the gist of it anyway.
You might want to store the allKeys and allValues arrays as class properties instead of having to go through them in all the tableview's delegate and datasource methods, but you should have all the info to build yuor table now.
Hope this helps :)
The key to what you need to do is recognizing that once your JSON string gets parsed into an object it becomes a series of nested NSArrays and NSDictionarys, and you just need to drilling through the values appropriately
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[transports allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [(NSArray*)[transports objectForKey:[[transports allKeys] objectAtIndex:section]] count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [transports allKeys];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// get transport category (e.g."public")
NSString *transportCategory = (NSString*)[[transports allKeys] objectAtIndex:[indexPath section]];
// get transport items belonging to the category
NSArray *items = (NSArray*)[transports objectForKey:transportCategory];
// get transport item for this row
NSDictionary *transportItem = [items objectAtIndex:[indexPath row]];
// extract values of transport item
NSString *transportName = [transportItem objectForKey:#"transport_name"];
NSString *transportID = [transportItem objectForKey:#"transport_id"];
cell.textLabel.text = transportName;
return cell;
}
NSDictionary *results = [jsonString JSONValue];
NSDictionary *allTypes = [results objectForKey:#"transport"];
NSArray *allTransportKeys = [allTypes allKeys];
Number of sections:
NSInteger numberOfSections = [allKeys count];
Number of rows in section:
NSString *key = [allKeys objectAtIndex:section];
NSArray *array = [allTypes objectForKey:key];
NSInteger numberOfRows = [array count];
Data at indexPath:
NSString *key = [allKeys objectAtIndex:indexPath.section];
NSArray *array = [allTypes objectForKey:key];
NSDictionary *itemDict = [array objectAtIndex:indexPath.row];
Then you can extract the data from itemDict.

Obj-C, iOS, How do I sort by value and not key, sortedArrayUsingSelector, currently #selector(compare:)]

I need to sort by value instead of Key, I think....
Heres where I populate my arrarys
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
while(sqlite3_step(statementTMP) == SQLITE_ROW)
{
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
NSArray *arr=[[NSArray alloc]initWithObjects:category,nil];
[arrayTmp setObject:arr forKey:[NSString stringWithFormat:#"%i",cid]];
[self.cidList addObject:[NSString stringWithFormat:#"%i",cid]];
[category release];
[arr release];
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
self.allCategories = arrayTmp;
[arrayTmp release];
Heres the method where the arrays are re-sorted.
- (void)resetSearch {
NSMutableDictionary *allCategoriesCopy = [self.allCategories mutableDeepCopy];
self.Categories = allCategoriesCopy;
[allCategoriesCopy release];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
[keyArray addObject:UITableViewIndexSearch];
[keyArray addObjectsFromArray:[[self.allCategories allKeys]
sortedArrayUsingSelector:#selector(compare:)]];
self.keys = keyArray;
[keyArray release];
}
This is a problem i've had for some time, last time I looked at this I could find an altervative to sortedArrayUsingSelector compare?
EDIT
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [Categories objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SectionsTableIdentifier ];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier: SectionsTableIdentifier ] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [Categories objectForKey:key];
NSLog(#"the selected cid is = %i",[key intValue]);
selectButton.enabled = YES;
}
Anyone?
Your obviously attempting to construct an array for use in the -[UITableviewDatasource sectionIndexTitlesForTableView:]. As such, you need an array that looks like this (pseudo-code):
[UITableViewIndexSearch, 0_sectionTitle, 1_sectionTitle, 2_sectionTitle, ...]
I think your immediate problem is that you try to add the UITableViewIndexSearch string constant to the array before you sort which makes it impossible for it end up as the first element unless all your other elements sort below U.
The fix is simple, just add the constant after the sort. You can clean the code up while you're at it:
NSMutableArray *secIdx=[NSMutableArray arrayWithCapacity:[[self.allCategories allKeys] count]];
[secIdx addObjectsFromArray:[self.allCategories allKeys]];
[secIdx sortUsingSelector:#selector(compare:)];
[secIdx insertObject:UITableViewIndexSearch atIndex:0];
self.keys=secIdx;
Note that secIdx is autoreleased so you don't have to release it.
Aside from this problem, your code has a lot of unnecessary/dangerous elements that will make your app fragile and hard to maintain.
You are using a lot of init for objects that you could use autoreleased convenience methods for. The 'init`s poise the risk of memory leaks but give you no advantage.
You need to wrap scalar values in objects so they can be easily managed in collections.
You are using an unnecessary array.
You can rewrite the first block like so:
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
NSNumber *cidNum; //... move variable declerations outside of loop
NSString *category; //.. so they are not continously recreated
[self.allCategories removeAllObjects]; //... clears the mutable dictionary instead of replacing it
while(sqlite3_step(statementTMP) == SQLITE_ROW){
cidNum=[NSNumber numberWithInt:(sqlite3_column_int(statementTMP, 0))];
category=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
//... adding the autoreleased category and cidNum to array/dictionary automatically retains them
[self.allCategories addObject:category forKey:cidNum];
[self.cidList addObject:cidNum];
//[category release]; ... no longer needed
//[arr release]; ... no longer needed
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
//self.allCategories = arrayTmp; ... no longer needed
//[arrayTmp release]; ... no longer needed
Use -sortedArrayUsingComparator: (or -sortedArrayUsingFunction:context: if you can't use blocks). Example:
NSDictionary *categories = [self allCategories];
NSArray *keysSortedByValue = [[categories allKeys] sortedArrayUsingComparator:
^(id left, id right) {
id lval = [categories objectForKey:left];
id rval = [categories objectForKey:right];
return [lval compare:rval];
}];
You could make a small model class Category and implement compare inside of it, then sort an array of those objects using that compare:.
Here's some info - How to sort an NSMutableArray with custom objects in it?
Perhaps you're looking for NSSortDescriptor (and the corresponding sort method, -[NSArray sortedArrayUsingDescriptors]) and friends?
If I understood correctly then what you wish to do to get categories from database & display it on a tableView with alphabetical sorting, index on right & search bar on top. Ideally, you would like to display the Contacts application kind of a view. If that's correct, use below code for fetching items from DB & rebuilding (or resetting) it -
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
NSMutableArray *arrayTmp = [[NSMutableArray alloc] init];
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
while(sqlite3_step(statementTMP) == SQLITE_ROW) {
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:category forKey:#"Category"];
[dict setObject:[NSNumber numberWithInt:cid] forKey:#"CID"];
[arrayTmp addObject:dict];
[dict release];
[category release];
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
self.allCategories = arrayTmp;
[arrayTmp release];
And then rebuild the items using this function -
- (void)rebuildItems {
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (int i = 0; i < allCategories.count; i++) {
NSString *name = [[allCategories objectAtIndex:i] objectForKey:#"Category"];
NSString *letter = [name substringToIndex:1];
letter = [letter uppercaseString];
if (isdigit([letter characterAtIndex:0]))
letter = #"#";
NSMutableArray *section = [map objectForKey:letter];
if (!section) {
section = [NSMutableArray array];
[map setObject:section forKey:letter];
}
[section addObject:[allCategories objectAtIndex:i]];
}
[_items release];
_items = [[NSMutableArray alloc] init];
[_sections release];
_sections = [[NSMutableArray alloc] init];
NSArray* letters = [map.allKeys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
for (NSString* letter in letters) {
NSArray* items = [map objectForKey:letter];
[_sections addObject:letter];
[_items addObject:items];
}
}
Now, displaying items in tableView, use below methods -
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
if (_sections.count)
return _sections.count;
else
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString *)title
atIndex:(NSInteger)index {
if (tableView.tableHeaderView) {
if (index == 0) {
[tableView scrollRectToVisible:tableView.tableHeaderView.bounds animated:NO];
return -1;
}
}
NSString* letter = [title substringToIndex:1];
NSInteger sectionCount = [tableView numberOfSections];
for (NSInteger i = 0; i < sectionCount; i++) {
NSString* section = [tableView.dataSource tableView:tableView titleForHeaderInSection:i];
if ([section hasPrefix:letter]) {
return i;
}
}
if (index >= sectionCount) {
return sectionCount-1;
} else {
return index;
}
}
- (NSArray*)lettersForSectionsWithSearch:(BOOL)withSearch withCount:(BOOL)withCount {
if (isSearching)
return nil;
if (_sections.count) {
NSMutableArray* titles = [NSMutableArray array];
if (withSearch) {
[titles addObject:UITableViewIndexSearch];
}
for (NSString* label in _sections) {
if (label.length) {
NSString* letter = [label substringToIndex:1];
[titles addObject:letter];
}
}
if (withCount) {
[titles addObject:#"#"];
}
return titles;
} else {
return nil;
}
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self lettersForSectionsWithSearch:YES withCount:NO];
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
if (_sections.count) {
NSArray* items = [_items objectAtIndex:section];
return items.count;
} else {
return _items.count;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (_sections.count)
return [_sections objectAtIndex:section];
return nil;
}
- (id)tableView:(UITableView *)tableView objectForRowAtIndexPath:(NSIndexPath *)indexPath {
if (_sections.count) {
NSArray *section = [_items objectAtIndex:indexPath.section];
return [section objectAtIndex:indexPath.row];
} else {
return [_items objectAtIndex:indexPath.row];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create your UITableViewCell.
// Configure the cell.
NSDictionary *dict = [self tableView:tableView objectForRowAtIndexPath:indexPath];
cell.textLabel.text = [dict objectForKey:#"Category"];
cell.detailTextLabel.text = [NSString stringWithFormat:%d, [[dict objectForKey:#"CID"] intValue]];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (isSearching)
return nil;
NSString *title = #"";
if (_sections.count) {
title = [[_sections objectAtIndex:section] substringToIndex:1];
} else {
return nil;
}
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
view.backgroundColor = [UIColor colorWithRed:(58/255.0) green:(27/255.0) blue:(6/255.0) alpha:1.0];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 1, 50, 18)];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:17.0];
label.text = title;
[view addSubview:label];
[label release];
return [view autorelease];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = [self tableView:tableView objectForRowAtIndexPath:indexPath];
NSLog(#"selected row id:%d, name:%#", [dict objectForKey:#"Category"], [[dict objectForKey:#"CID"] intValue]);
}
The rest part is implementing the UISearchBarDelegate and implementing searching of tableView which can be done using below code:
- (void)searchBar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText {
[_sections removeAllObjects];
[_items removeAllObjects];
if([searchText isEqualToString:#""] || searchText == nil) {
[self rebuildItems];
return;
}
NSInteger counter = 0;
for(NSDictionary *dict in allCategories) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRange r = [[dict objectForKey:#"Category"] rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound) {
if(r.location == 0) {
[_items addObject:dict];
}
}
counter++;
[pool release];
}
[contactList reloadData];
}
Hope this is what you're looking for.
On your sorting function u should try this:
NSArray *cntxt; //im not sure this is the correct type that ur using on keyArray
[keyArray addObjectsFromArray:[self.allCategories allKeys]];
[keyArray sortUsingFunction:compareFunction context:cntxt];
And the compare function you modify to your needs
NSInteger compareFunction(id x, id y, void *context) {
//NSArray *ctxt = context;
NSArray *c1 = x;
NSArray *c2 = y;
if ([c1 value] < [c2 value])
return NSOrderedDescending;
else if ([c1 value] > [c2 value])
return NSOrderedAscending;
else
return NSOrderedSame;
}
Edit: After reading your comments and after relooking at your code, it seems like that your keyArray as objects of the type NSString, so you should change:
NSInteger compareFunction(id x, id y, void *context) {
//NSString *ctxt = context;
NSString *c1 = x;
NSString *c2 = y;
NSComparisonResult result;
result = [c1 compare:c2];
if (result<0)
return NSOrderedAscending;
else if (result>0)
return NSOrderedDescending;
else
return NSOrderedSame;
}

UISearchBar in iPhone/iPad application

I have data like this...(All the data comes from .plist file...)
Searching Array - (
{
FirstName = "Ramesh";
LastName = "Bean";
EmpCode = 1001;
},
{
FirstName = "Rohan";
LastName = "Rathor";
EmpCode = 102;
},
{
FirstName = "Priya";
LastName = "Malhotra";
EmpCode = 103;
},
{
FirstName = "Mukesh";
LastName = "Sen";
EmpCode = 104;
},
{
FirstName = "Priya";
LastName = "Datta";
EmpCode = 105;
}
)
I want implement search data from this array on the basis of FirstName (key).
I am able to search data with the "FirstName(Key)"
but after filtering data suppose i clicked Row( in the data) which is displayed in the TableView. It Navigate me to New-Controller with all the information of that particular employee (like: FirstName,LastName,EmpCode).
How can i get information?
As i gone through the search sample codes.
Here is my search code...
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
NSInteger TotalNoOfRecords=[self.SearchtableDataSource count];
for (int i=0;i<TotalNoOfRecords;i++)
{ NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:i];
NSArray *array = [dictionary objectForKey:#"FirstName"];
[searchArray addObject:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
[copyListOfItems addObject:sTemp];
}
}
How can i improve this code?....Please guide me... [searchArray release]; searchArray = nil;
How we maintain all the "Keys(FirstName,LastName,EmpCode)" in the searchArray please help me out? Thanks...
I think the best approach would be to make an array of NSDictionary which has value for three keys namely "FirstName", "LastName", "EmpCode"
now to filter the data according to "FirstName" use NSPredicate instead of for loop,
NSString *searchText = searchBar.text;
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"FirstName like[cd] %#",searchText];
NSArray* filteredArray = [self.SearchtableDataSource filteredArrayUsingPredicate:predicate];
In method cellForRowAtIndexPath
NSDictionary* currentEmp = [filteredArray objectAtIndex:inddexPath.row];
display the information in this currentEmp.
Similarly in didSelectRowAtIndexPath
NSDictionary* currentEmp = [filteredArray objectAtIndex:inddexPath.row];
and pass this dictionary in the next ViewController in which u want to dispaly the detail of the current employ.
if u have two table views one that of searchDisplayController (showing the filtered result)
and one which is showing the whole result, then u can track this by having a BOOL variable tacking that is if filtering is active or not.
Here is what i have done and its working fine with me(tested it). I have taken one IBOutlet of UISearchBar so here is the code for ur .h file
#interface SearchForEmp : UIViewController<'UISearchDisplayDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource> {
IBOutlet UISearchBar* mySearchBar;
UISearchDisplayController* mySearchDisplayController;
NSMutableArray* allEmp;
NSMutableArray* filteredEmp;
BOOL isFilatering;
}
#end
Now in .m file
-(void)viewDidLoad
{
[super viewDidLoad];
mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];
mySearchDisplayController.searchResultsDelegate = self;
mySearchDisplayController.searchResultsDataSource = self;
mySearchDisplayController.delegate = self;
isFilatering = NO;
filteredEmp = [[NSMutableArray alloc] init];
allEmp = [[NSMutableArray alloc] init];
NSDictionary *temp;
for (int i = 0; i < 30; i++) {
temp = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"FirstName_%d",i],#"FirstName",[NSString stringWithFormat:#"LastName_%d",i],#"LastName",[NSNumber numberWithInt:1000+i],#"EmpCode",nil];
[allEmp addObject:temp];
}
}
for e.g purpose i have thake an array of 30 Dictionaries, each with a unique name.For table view data source and delegate .....
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFilatering) {
return [filteredEmp count];
}
else {
return [allEmp count];
}
return [allEmp count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] init] autorelease];
}
NSDictionary* temp;
if (isFilatering) {
temp = [filteredEmp objectAtIndex:indexPath.row];
}
else {
temp = [allEmp objectAtIndex:indexPath.row];
}
cell.textLabel.text = [NSString stringWithFormat:#"%# %#",[temp objectForKey:#"FirstName"],[temp objectForKey:#"LastName"]];
return cell;
}
Now as far as searching is concerned here is what u need to do .......
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSPredicate* predicate = [[NSPredicate predicateWithFormat:#"self.FirstName contains %#",mySearchBar.text] retain];
filteredEmp = [[allEmp filteredArrayUsingPredicate:predicate] retain];
}
-(void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
isFilatering = YES;
}
-(void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
isFilatering = NO;
}
I hope that helps you understanding the things, dont forget to add retain in line
filteredEmp = [[allEmp filteredArrayUsingPredicate:predicate] retain];
because method filteredArrayUsingPredicate: is an accessor method and its retain count is handled by the NSArray so have access to the filtered array u need to pass a retain msg to it.