Raphael Lim Raphael Lim - 3 months ago 15
Objective-C Question

App keeps crashing creating a PygLatin Game - Objective C

I am new to objective C programming.

I created a PygLatin application but it keeps crashing it. Do tell me if you have spotted any problems with my code.


Terminating app due to uncaught exception 'NSRangeException', reason: ' -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'
First throw call stack:


would appreciate all the help I can get thanks! :)

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.userInputTextField.delegate = self;

self.userInputTextField.text = @"";
}

-(void)print: (NSString*)printWords {
self.resultLabel.text = @"%@", printWords;
}

-(void)charsplitter: (NSArray*)charArraysplitter {
//word selection loop
int indexCount = 0;
for(indexCount = 0; indexCount < charArraysplitter.count; indexCount++)
{
self.wordsToBeSplit = charArraysplitter[indexCount];

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self.wordsToBeSplit length]];

[self.wordsToBeSplit enumerateSubstringsInRange:NSMakeRange(0, self.wordsToBeSplit.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characters addObject:substring];
}];
[self vowelsComparator:characters];
}
}

-(void)vowelsComparator: (NSArray*)comparator {
self.myVowels = [NSArray arrayWithObjects: @"a", @"e", @"i", @"o",@"u", nil];
int charIndex;
self.subsequentCharCount = 0;
for(charIndex = 0; charIndex < comparator.count; charIndex++)
//loops to find if first character is a vowel
if([self.myVowels containsObject:comparator[0]]){
[self print: self.userInputTextField]; NSLog(@"working fine:");
}else{
//loops to find other vowels
while (self.subsequentCharCount < comparator.count){
self.subsequentCharCount++;
if ([self.myVowels containsObject:comparator[self.subsequentCharCount]]){
//moving the consonants behing the vowels
NSLog(@"working fine:");
NSString *combinedWords = [[self.wordsToBeSplit substringFromIndex:self.subsequentCharCount]stringByAppendingString:[self.wordsToBeSplit substringToIndex:self.subsequentCharCount]];
NSString *completedWord = [combinedWords stringByAppendingString:@"ay"];
[self print: completedWord];
}
};
}
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];//resigns the keyboard every time return button is pressed
return YES;
}

- (IBAction)pygButton:(id)sender
{
self.inputText = [self.userInputTextField.text lowercaseString];//user input is lowercase
NSArray *wordsArray = [self.inputText componentsSeparatedByString: @" "]; //separate words into arrays.
[self charsplitter: wordsArray];
}

@end

Answer

put
self.subsequentCharCount++;
at the end of while loop means below
[self print: completedWord];