nsmutablearray-替换物品导致例外……帮助!
-
23-08-2019 - |
题
我是OBJ-C的新手。我需要更好地学习,所以请告诉我我做错了什么。
我有一系列图像。...在Exec的各个点上,我需要用前面的图像之一替换最后一个元素...因此,最后一个图像总是在以前复制其中一个图像。当我进行替换时,它会引发异常!如果我删除对setCorreCtimage的调用,则可以使用。
在过去的几个小时中,无法弄清楚这一点:-(
控制器中的声明。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];
}
解决方案
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];
不隶属于 StackOverflow