Search code examples
iosnsstringnsmutablearraynsarray

How to split an NSArray of sorted NSStrings into NSMutableArray of NSMutableArrays


I would like to know how to split an NSArray of alphabetically sorted NSStrings into an NSMutableArray of NSMutableArrays.

For instance say my NSArray looks like this

Alice
Awesome
Bacon
Beef
Hat
Hooters
Horse

I would like the NSMutableArray of NSMutableArrays to look like this

-- Alice
   Awesome

-- Bacon
   Beef

-- Hat
   Hooters
   Horse

I understand it will most likely need to be done using for at for loop however im just not sure how to do this catching the first letter.

This is the pseudo code I have come up with

NSMutableArray *mainArray = [NSMutableArray alloc] init];

for (int i = 0; i < [sortedArray count]; i++) {
  NSMutableArray *subArray = [NSMutableArray alloc] init];
  NSString *currentString = [sortedArray objectAtIndex:i];

  if (figure out if first character of currentString is what it is supposed to be){
    [subArray addObject:currentString];
  }

  [mainArray addObject:subArray];
}

I know this is off and the for loop logic is way off, but that and finding the first letter is where I am having the issue. For all I know there is a much faster delegate method that will do everything automatically, but this is why I asked the question.


Solution

  • NSString* currentLetter;
    NSMutableArray* currentSubArray;
    
    for( NSString* name in sortedArray ){
    
        NSString* firstLetterOfName = [name substringToIndex:1];
    
        if( [firstLetterOfName isEqualToString:currentLetter] ){
            // Name first letter is equal to the last one, so just add to current sub array
            [currentSubArray addObject:name];
        }
        else{
            // New letter found, create a new sub array and add to main one
    
            currentSubArray = [[NSMutableArray alloc] initWithObjects:name, nil]; // needs nil
            currentLetter = firstLetterOfName;
            [mainArray addObject:currentSubArray];
        }
    
    }
    

    Something like that?