2011-11-07 4 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) 

당신은 내가 이유를 정확하게 XCode 4.2

확실하지 업데이트되지 않습니다 Big Nerd Ranch Cocoa® Programming for Mac® OS X (3rd Edition)에서 작업 코코아를 배우고 추측 수 있듯이 내 색인은 범위를 넘어서는 것이거나 정확히 무엇을 의미 할 것입니다. 감사.

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

for 라인의 끝에서 그 ;을 제거

답변

1

는 동일한 오타의 두 인스턴스가 있습니다. 있는 그대로, 당신은 그 두 for 루프 안의 명령을 실행하고 있습니다. 당신이 쓴 것은하는 것과 같습니다 Bavarious 응답에 추가

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 * 감사합니다! – ian

1

, 내가 사용하는 일반적으로 당신을 제안 @ 당신 objectAtIndex 사용할 때/@ 캐치 블록을 시도 : 선택 (그 메소드가 예외를 던질 수) 이 방법으로 코드를 시행하게되고 앱이 멈추지 않게됩니다. 따라서 :

@try { 

    [array addObject:newNumber]; 

} @cacth (NSException *exception) { 

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

감사합니다. 이것은 문자 그대로 두 번째 코코아 프로그램이지만 내 코드에 추가했습니다. 사용할 수있는 좋은 개념. – ian

관련 문제