How to partition NSArray in sections of a UITableView in alphabetical order

I'm having trouble using an indexed table with section headers. Currently, I have indexes on the right side, and I am displaying section headings correctly, headings only show if there is data inside this section.

The problem I am facing is to split NSArray so that I can correctly calculate the number ofOfRowsInSections. Currently, I have the correct number of sections displayed with the correct headers, but all the data is in each section, and not divided according to the first letter of the name.

Here is a screenshot of what it currently looks like: All of the data goes into each sections, 5 rows in each.  The number of sections (3) is correct

All data comes in each section, 5 lines. The number of sections (3) is correct.

:

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

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{

    NSMutableSet *mySet = [[NSMutableSet alloc] init];

    BRConnection *connection = nil;
    NSMutableArray *firstNames = [[NSMutableArray alloc] init];
    for (connection in _connections)
    {
        [firstNames addObject:connection.firstName];
    }
    firstNamesArray = firstNames;
    NSLog(@"%@", firstNamesArray);
    for ( NSString *s in firstNames)
    {
        if ([s length] > 0)
            [mySet addObject:[s substringToIndex:1]];
    }

    NSArray *indexArray = [[mySet allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    firstLetterArray = indexArray;

    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    if ([title isEqualToString:@"{search}"])
    {
        [tableView setContentOffset:CGPointMake(0.0, -tableView.contentInset.top)];
        return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
    }
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConnectionCell"];

    // Display connection in the table cell
    BRConnection *connection = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        connection = [searchResults objectAtIndex:indexPath.row];
    } else {
        connection = [_connections objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = connection.fullName;
    cell.textLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:18];
    cell.detailTextLabel.text = connection.company;
    cell.detailTextLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:12];

    return cell;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    NSUInteger sections = [firstLetterArray count];
    return sections;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];

    } else {
        return [_connections count];
    }
}

, NSArray , . !

+4
3

_connections? , _connections . _connections .

, , NSMutableArray of NSMutableArray . , , , . :

NSString *currentPrefix;

// Store sortedConnections as a class variable (as you've done with _connections)
// so you can access it to populate your table
sortedConnections = [[NSMutableArray alloc] init];

// Go through each connection (already ordered alphabetically)
for (BRConnection *connection in _connections) {

    // Find the first letter of the current connection
    NSString *firstLetter = [connection.fullName substringToIndex:1];

    // If the last connection prefix (stored in currentPrefix) is equal
    // to the current first letter, just add the connection to the final
    // array already in sortedConnections
    if ([currentPrefix isEqualToString:firstLetter]) {
        [[sortedConnected lastObject] addObject:connection];
    }

    // Else create a new array in sortedConnections to contain connections starting
    // with this current connection letter.
    else {
        NSMutableArray *newArray = [[NSMutableArray alloc] initWithObject:connection];
        [sortedConnections addObject:newArray];
    }

    // To mark this latest array prefix, set currentPrefix to contain firstLetter
    currentPrefix = firstLetter;
}

( , .)

, , [sortedConnections objectAtIndex:section] _connections:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [[sortedSearchResults objectAtIndex:section] count]; // hypothetically
    } else {
        return [[sortedConnections objectAtIndex:section] count];
    }
}

[sortedConnections objectAtIndex:indexPath.section]:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConnectionCell"];

    // Display connection in the table cell
    BRConnection *connection = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        connection = [[sortedSearchResults objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; // hypothetically
    } else {
        connection = [[sortedConnections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = connection.fullName;
    cell.textLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:18];
    cell.detailTextLabel.text = connection.company;
    cell.detailTextLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:12];

    return cell;
}
+6

, , , , =)

NSArray *names = @[@"Ana Carolina", @"Ana carolina", @"Ana luiza", @"leonardo", @"fernanda", @"Leonardo Cavalcante"];

NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
for( NSString*string in names ){
    [firstCharacters addObject:[[string substringToIndex:1] uppercaseString]];
}
NSArray *allLetters = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
int indexLetter = 0;
NSMutableArray *separeNamesByLetters = [NSMutableArray new];



for (NSString *letter in allLetters) {
    NSMutableDictionary*userBegeinsWith = [NSMutableDictionary new];
    [userBegeinsWith setObject:letter forKey:@"letter"];
    NSMutableArray *groupNameByLetters = [NSMutableArray new];
    NSString *compareLetter1 = [NSString stringWithFormat:@"%@", allLetters[indexLetter]];
    for (NSString*friendName in names) {
        NSString *compareLetter2 = [[friendName substringToIndex:1] uppercaseString];

        if ( [compareLetter1 isEqualToString:compareLetter2] ) {
            [groupNameByLetters addObject:friendName];
        }
    }
    indexLetter++;
    [userBegeinsWith setObject:groupNameByLetters forKey:@"list"];
    [separeNamesByLetters addObject: userBegeinsWith];
}



NSLog(@"%@", separeNamesByLetters);

:

 (
        {
        letter = A;
        list =         (
            "ana carolina",
            "Ana carolina",
            "Ana luiza"
        );
    },
        {
        letter = F;
        list =         (
            fernanda
        );
    },
        {
        letter = L;
        list =         (
            leonardo,
            "Leonardo Cavalcante"

        )
    }
)
+5

Just in case, you have custom objects, a small modification in @Leo

NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
        for( ETUser *user in self.follwings){
            [firstCharacters addObject:[[user.name substringToIndex:1] uppercaseString]];
        }
        NSArray *allLetters = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
        int indexLetter = 0;
        NSMutableArray *separeNamesByLetters = [NSMutableArray new];


        for (NSString *letter in allLetters) {

            NSMutableDictionary*userBegeinsWith = [NSMutableDictionary new];

            [userBegeinsWith setObject:letter forKey:@"letter"];

            NSMutableArray *groupNameByLetters = [NSMutableArray new];

            NSString *compareLetter1 = [NSString stringWithFormat:@"%@", allLetters[indexLetter]];

            for (ETUser *user in self.follwings) {

                NSString *compareLetter2 = [[user.name substringToIndex:1] uppercaseString];

                if ( [compareLetter1 isEqualToString:compareLetter2] ) {

                    [groupNameByLetters addObject:user];
                }
            }
            indexLetter++;
            [userBegeinsWith setObject:groupNameByLetters forKey:@"list"];
            [separeNamesByLetters addObject: userBegeinsWith];
        }

        self.follwings = [[NSMutableArray alloc]initWithArray:separeNamesByLetters];
0
source

Source: https://habr.com/ru/post/1545484/


All Articles