2011-11-07 148 views
0

我正在做一个教程,并得到以下错误。NSRangeException超越界限未捕获异常

我的代码:

#import <Foundation/Foundation.h> 

int main (int argc, const char * argv[]) 
{ 
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    @autoreleasepool 
    { 

    NSMutableArray *array; 
    array = [[NSMutableArray alloc] init]; 
    int i; 
    for(i = 0; i < 10; i++); 
    { 
     NSNumber *newNumber; 
     newNumber = [[NSNumber alloc] initWithInt:(i * 3)]; 
     [array addObject:newNumber]; 
    } 


    for(i = 0; i < 10; i++); 
    { 
     NSNumber *numberToPrint; 
     numberToPrint = [array objectAtIndex:i]; 
     NSLog(@"The number at index %d is %@", i, numberToPrint); 
    } 
    } 
    //[pool drain]; 
    return 0; 
} 

错误:

GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 8 20:32:45 UTC 2011) 
Copyright 2004 Free Software Foundation, Inc. 
GDB is free software, covered by the GNU General Public License, and you are 
welcome to change it and/or distribute copies of it under certain conditions. 
Type "show copying" to see the conditions. 
There is absolutely no warranty for GDB. Type "show warranty" for details. 
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000 
[Switching to process 26323 thread 0x0] 
2011-11-06 21:46:26.506 lottery[26323:707] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds [0 .. 0]' 
*** First throw call stack: 
(
    0 CoreFoundation      0x00007fff976d9286 __exceptionPreprocess + 198 
    1 libobjc.A.dylib      0x00007fff932a3d5e objc_exception_throw + 43 
    2 CoreFoundation      0x00007fff976669f2 -[__NSArrayM objectAtIndex:] + 274 
    3 lottery        0x0000000100000e49 main + 345 
    4 lottery        0x0000000100000ce4 start + 52 
    5 ???         0x0000000000000001 0x0 + 1 
) 
terminate called throwing an exceptionsharedlibrary apply-load-rules all 
(gdb) 

正如您可以猜到我学习可可工作了Big Nerd Ranch Cocoa® Programming for Mac® OS X (3rd Edition)这是不完全更新的XCode 4.2

不知道为什么我的指数会超越界限或者这意味着什么。谢谢。

回答

1

你有相同的错字的两个实例:

for(i = 0; i < 10; i++); 

for行的末尾删除那些;。现在,您在这两个for循环内执行无指令。什么你写等同于:

for(i = 0; i < 10; i++) 
{ 
} 

{ 
    NSNumber *newNumber; 
    newNumber = [[NSNumber alloc] initWithInt:(i * 3)]; 
    [array addObject:newNumber]; 
} 

for(i = 0; i < 10; i++) 
{ 
} 

{ 
    NSNumber *numberToPrint; 
    numberToPrint = [array objectAtIndex:i]; 
    NSLog(@"The number at index %d is %@", i, numberToPrint); 
} 
+0

* facepalm * thanks! – ian

1

除了Bavarious响应,我建议你作为一般规则,使用@尝试/ @ catch块当您使用objectAtIndex:选择(该方法可以抛出异常) ,这样你将执行你的代码,你的应用程序不会冻结。所以:

@try { 

    [array addObject:newNumber]; 

} @cacth (NSException *exception) { 

    NSLog(@"catched error: %@", exception.description); 
} 
+0

谢谢。这实际上是我的第二个Cocoa程序,但我将它添加到我的代码中。好的概念使用。 – ian

相关问题