0

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

我有一个图像数组......在执行的各个点我需要用前面的图像之一替换最后一个元素......所以最后一个图像总是复制之前的一个图像。当我进行替换时,它会引发异常!如果我删除对 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];
}
4

1 回答 1

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];
于 2009-07-05T04:36:32.280 回答