0

I am a problem with counting values in a plist file ,the problem is the if statement should check if the value is greater than objects in my plist , then stop moving to next pages , here is my code but :

    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]];

but after when photos reach to the last page , application will crash , debugger message :

'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (30) beyond bounds (30)'
*** First throw call stack:
1
  • 2
    [NSArray count] gives you the number of items in the array, not the index of the last item. Commented Jun 1, 2012 at 12:46

3 Answers 3

5

try

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

the reason it crashes is, that count will give the number of objects, but when accessing each, you start with 0, so [array count]-1 is the last index.

Sign up to request clarification or add additional context in comments.

Comments

3

Change

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

to

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

If you have 30 items in your array, the largest accessible index is 29 because the first element is at index 0.

Comments

1

You want:

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

Since it starts at 0 and if you try to get object at index equal to the count, it's reading past the end of the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.