Reputation: 73
I was getting this error when running my code 2013-02-23 10:52:54.063 Calculator[31319:11303] * Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString characterAtIndex:]: Range or index out of bounds' * First throw call stack: (0x1c90012 0x10cde7e 0x1c8fdeb 0x1c56c0d 0x2d4b 0x10e1705 0x18920 0x188b8 0xd9671 0xd9bcf 0xd8d38 0x4833f 0x48552 0x263aa 0x17cf8 0x1bebdf9 0x1bebad0 0x1c05bf5 0x1c05962 0x1c36bb6 0x1c35f44 0x1c35e1b 0x1bea7e3 0x1bea668 0x1565c 0x22c2 0x21f5 0x1) My application usually takes the string entered in the textbox and converts to ascii values and then I wrote a small algorithm for it.Below is the piece of code how I am converting the string to ascii
for (int i=0; i<[first length]; i++) {
unichar ch = [first characterAtIndex:i];
firsttotal = firsttotal +ch;
}
for (int j=0; j<[second length]; j++) {
unichar chi = [first characterAtIndex:j];
secondtotal = secondtotal +chi;
}
Upvotes: 1
Views: 180
Reputation: 35308
Unless I'm reading your code wrong, it should be this:
for (int i=0; i<[first length]; i++) {
unichar ch = [first characterAtIndex:i];
firsttotal = firsttotal +ch;
}
for (int j=0; j<[second length]; j++) {
unichar chi = [second characterAtIndex:j]; // <-- THIS LINE
secondtotal = secondtotal +chi;
}
You're trying to take characters from first
that may be beyond the end of the string.
Upvotes: 1
Reputation: 17916
Your second loop is pulling characters out of the first string. This is probably not what you intend. Because you iterate for each character in the second string, you will get this error with your code as posted above any time the second string is longer than the first.
Try changing the line
unichar chi = [first characterAtIndex:j];
to
unichar chi = [second characterAtIndex:j];
and this problem will disappear.
Upvotes: 0