2012-06-01 2 views
0

plist 파일의 값을 계산하는 데 문제가 있습니다. 문제는 if 문이 값이 내 plist의 개체보다 큰지 확인한 후 다음 페이지로 이동하지 못하게하는 문제입니다. 코드 만 : [배열 수]와 관련된 문제

picturesDictionary = [NSDictionary dictionaryWithContentsOfFile: 
            [[NSBundle mainBundle] pathForResource:@"images" ofType:@"plist"]]; 
arrays = [picturesDictionary objectForKey:@"PhotosArray"]; 

    int photoCount = [arrays count]; 


if ((photoNumber < 1) || (photoNumber > photoCount)) return nil; 

controller = [BookController rotatableViewController]; 

PhotosInAlbum.image = [UIImage imageNamed:[arrays objectAtIndex:pageNumber]]; 

하지만 사진은 마지막 페이지에 도달하면 이후

는 응용 프로그램이 충돌합니다, 디버거 메시지 :

'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (30) beyond bounds (30)' 
*** First throw call stack: 
+2

'[NSArray count]'는 마지막 항목의 색인이 아니라 배열의 항목 수를 알려줍니다. – Manuel

답변

5

if ((pageNumber < 0) || (pageNumber > (photoCount-1))) return nil;

시도 그 이유는 충돌이 개체의 수를 줄 것이지만 각 개체에 액세스 할 때는 0부터 시작하므로 [배열 수] -1이 마지막 색인입니다. 첫 번째 요소는 당신이 원하는 0

3

변경

if ((pageNumber < 1) || (pageNumber > photoCount)) return nil; 

if ((pageNumber < 0) || (pageNumber >= photoCount)) return nil; 

당신이 당신의 배열의 30 개 항목이있는 경우에, 가장 큰 접근 지수는 29이다 :

if ((pageNumber < 0) || (pageNumber >= photoCount)) return nil; 

0에서 시작하고 인덱스와 같은 수의 객체를 얻으려고하면 배열의 끝에서부터 읽습니다.