Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Add Alphabetical Header to UITableView with sorted Array

I'm sorting my array by last name alphabetically. I'd like to separate this into sections with the appropriate header above each section (A, B, C, etc.).

Here's what I've tried below:
// View Did Load
- (void)viewDidLoad {
    [super viewDidLoad];

    self.alphabetsArray =[[NSMutableArray 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];
}

// Here is where I refresh the data and sort it based on last name
- (void)refreshData {
    [[PCMSSessionManager sharedSession] refreshPCMSDataWithCompletion:^(BOOL success, NSString *errorMessage, id resultObject) {
        if (success) {
            NSLog(@yay!);
            self.membersArray = [[PCMSSessionManager sharedSession] memberArr];

            // Let's sort the array
            self.sortedArray = [self.membersArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
                NSString *first = [(PCMSMember*)a lastName];
                NSString *second = [(PCMSMember*)b lastName];
                return [first compare:second];
            }];

            [self.tableView reloadData];

        } else {
            NSLog(@boooo!!!!);
        }
    }];
}

// Here's my table data
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sortedArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @cellIdentifier;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    // Configure the cell...
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    if (self.isPhysician == YES) {
        PCMSMember *currentMember = [self.sortedArray objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@%@ %@", currentMember.firstName, currentMember.lastName];
    }

    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.alphabetsArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [self.alphabetsArray indexOfObject:title];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.alphabetsArray objectAtIndex:section];
}

Right now this is just crashing on me.

I'm getting this message:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 462 beyond bounds [0 .. 25]'

Replies

  • BrianSlickBrianSlick Treadmill Desk Ninja Posts: 10,687 @ @ @ @ @ @ @ @
  • martinsahamartinsaha ChennaiPosts: 8 Noob
    Follow these steps:

    make an index alphabet array with all starting alphabet of words you are going to populate
    Now sort it:
    //sorting for english language
    indexAlphabetArray = (NSMutableArray *)[indexAlphabetArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    Now implement
    -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
    {
        return indexAlphabetArray;
    }
    
    Final suggestion, take a dictionary of all names and group name with firstletter as key in dictionary, Eg.:
    nameDictionary:{
    A:(
    Astart,
    Astop,
    )
    b:(
    bstart,
    bstop,
    )
    }
    In this way indexAlphabetArray = [nameDictionary allKeys];
    Edit: Lets make it more easy for you:
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [[nameDictionary valueForKey:[indexAlphabetArray objectAtIndex:section]] count];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *kCellID = @cellID;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
        }
        NSArray *nameArray = [nameDictionary valueForKey:[indexAlphabetArray objectAtIndex:indexPath.section]];
        cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];
        return cell;    
    }
    
  • RickSDKRickSDK Posts: 1,237 @ @ @ @
    here's one problem:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sortedArray.count;
    }

    that should be:
    return self.alphabetsArray.count;

    that should fix your crash issue. You really want 26 sections right? not a new section for every item in sortedArray.
Sign In or Register to comment.