nick
nick

Reputation: 2853

NSMutableArray insertObject:atIndex causing crashes

I'm working on a slideshow creation app for the iPad and running into a little trouble when I let the user rearrange the slides. When the slideDropped method is called, if I just remove the slide then add it on the end of the slideshow then everything works fine. If I take say slide 2 of a 5 slide slideshow and move it to slide 3 then when I try to loop through slideshow.slides (which is just a NSMutableArray) then it crashes with a bad access error on the new slide.

-(void)slideDropped:(Slide *)slide
{
    int destIndex = (int)(slide.frame.origin.x) / 152;
    destIndex = MIN(destIndex, slideshow.slides.count - 1);
    destIndex = MAX(0, destIndex);
    int sourceIndex = [slideshow.slides indexOfObject:slide];
    [slideshow removeSlideAtIndex:sourceIndex];
    if(destIndex >= slideshow.slides.count)
        [slideshow addSlide:slide];
    else
        [slideshow insertSlide:slide atIndex:destIndex];
    [self arrangeSlides];
}

-(void)arrangeSlides
{
    [scrSlideshow.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    int x = 0;
    NSLog(@"There are %i slides",slideshow.slides.count);
    for(Slide* slide in slideshow.slides)
    {
        NSLog(@"%@",slide);//crashes here on the new slide if I insert at a specific index rather than appending the slide to the end
        CGRect frame = CGRectMake(x++ * 152, 21, 150, 150);
        slide.frame = frame;
        [scrSlideshow addSubview:slide];
    }
    [scrSlideshow setContentSize:CGSizeMake(slideshow.slides.count * 152, 150)];
}

//in the Slideshow class

-(void)addSlide:(Slide *)slide
{
    [slides addObject:slide];
}

-(void)removeSlideAtIndex:(int)index
{
    [slides removeObjectAtIndex:index];
}

-(void)insertSlide:(Slide *)slide atIndex:(int)index
{
    [slides insertObject:slides atIndex:index];
}

Any ideas as to what I could be doing wrong? I suspect I'm not managing the slide properly but I'm not sure how else to do it.

Upvotes: 0

Views: 749

Answers (1)

Halen
Halen

Reputation: 456

Look at the bottom of that code. You have insertObject:slides. Should this just be "slide" or did you intend for it to be plural? That could be your problem

Upvotes: 2

Related Questions