Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5985807
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T22:34:59+00:00 2026-05-22T22:34:59+00:00

I need to sort by value instead of Key, I think…. Heres where I

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T22:34:59+00:00Added an answer on May 22, 2026 at 10:34 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I can sort by key or value, but I need it sorted by value,
I have a the need for key value pair that I wish to sort
I have List[(String,String)] and I need to sort them by the 2nd value and
I have a key => value table I'd like to sort in Lua. The
Is there some sort of ASP validator which, instead of having to select specific
I need to sort a flat file by third column leaving first column intact
I need to sort list of strings in the alphabetical order: List<String> list =
I need to sort nodes in xml. I have the following code which successfully
I need to sort on a date-field type, which name is mod_date. It works
I need to sort close to a 1,00,000 floating point entries in Delphi. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.