NSMutableArray - 替换项目会导致异常......帮助!

时间:2009-07-05 04:14:33

标签: iphone exception uiimageview nsmutablearray

我是Obj-C的新手。我需要更好地学习这个,所以请告诉我我做错了什么..

我有一个图像数组....在exec的各个点我需要用前面的图像替换最后一个元素...所以最后一个图像总是复制其中一个图像。 当我进行更换时,会抛出异常!如果我删除对setCorrectImage的调用,它就可以工作。

现在最近几个小时无法解决这个问题: - (


controller.h中的声明如下 -

NSMutableArray      *imageSet;
UIImage *img, *img1, *img2, *img3, *img4, *img5;

数组在控制器中初始化 -

-(void)loadStarImageSet
{

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:AWARD_STAR_0 ofType:@"png"], 
    *imagePath1 = [[NSBundle mainBundle] pathForResource:AWARD_STAR_1 ofType:@"png"],
    *imagePath2 = [[NSBundle mainBundle] pathForResource:AWARD_STAR_2 ofType:@"png"],
    *imagePath3 = [[NSBundle mainBundle] pathForResource:AWARD_STAR_3 ofType:@"png"],
    *imagePath4 = [[NSBundle mainBundle] pathForResource:AWARD_STAR_4 ofType:@"png"],
    *imagePath5 = [[NSBundle mainBundle] pathForResource:AWARD_STAR_5 ofType:@"png"]    
    ;

    img  = [[UIImage alloc] initWithContentsOfFile:imagePath];
    img1 = [[UIImage alloc] initWithContentsOfFile:imagePath1];
    img2 = [[UIImage alloc] initWithContentsOfFile:imagePath2];
    img3 = [[UIImage alloc] initWithContentsOfFile:imagePath3];
    img4 = [[UIImage alloc] initWithContentsOfFile:imagePath4];
    img5 = [[UIImage alloc] initWithContentsOfFile:imagePath5];


    if(imageSet != nil)
    {
        [imageSet release];
    }
    imageSet = [NSArray arrayWithObjects:img, img1, img2, img3, img4, img5, img, nil];

    [imageSet retain];
}

当视图出现时,会发生这种情况 -

(void)viewDidAppear:(BOOL)animated
{
    [self processResults];

    [self setCorrectImage];

    [self animateStar];
}


-(void)setCorrectImage
{
    // It crashes on this assignment below!!!!!

    [imageSet replaceObjectAtIndex:6 withObject:img4]; // hard-coded img4 for prototype... it will be dynamic later
}

-(void) animateStar
{
    //Load the Images into the UIImageView var - imageViewResult
    [imageViewResult setAnimationImages:imageSet];

    imageViewResult.animationDuration = 1.5;
    imageViewResult.animationRepeatCount = 1;
    [imageViewResult startAnimating];
}

1 个答案:

答案 0 :(得分:2)

imageSet = [NSArray arrayWithObjects:img, img1, img2, img3, img4, img5, img, nil];

您正在此处创建NSArray(非可变数组)对象,并将其分配给imageSet变量。这非常糟糕,因为imageSet被声明为NSMutableArray *类型,并且您创建的对象的类型为NSArray,而NSArray不是NSMutableArray的子类型}。

因此发生错误是因为该对象实际上是NSArray对象,而不是NSMutableArray(或其子类),因此不支持replaceObjectAtIndex:withObject:消息。

您应该创建一个NSMutableArray对象:

imageSet = [NSMutableArray arrayWithObjects:img, img1, img2, img3, img4, img5, img, nil];
相关问题