【问题标题】:NSMutableArray - replacing an item causes exception...help!NSMutableArray - 替换项目会导致异常...帮助!
【发布时间】:2009-07-05 04:14:33
【问题描述】:

我是 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];
}

【问题讨论】:

    标签: iphone exception uiimageview nsmutablearray


    【解决方案1】:
    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];
    

    【讨论】:

    • 啊,谢谢!我好蠢!如果你盯着一段代码太久会发生这种情况。它就在我面前,我没看到……谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多