I am a newbie in Obj-C. I need to learn this better so please tell me what I am doing wrong..
I have an array of Images…. at various points of exec I need to replace the last element with one of the preceding images… so the last image always replicates one of the images before.
When I do the replacement, it throws an exception! If I remove the call to setCorrectImage, it works.
Am not able to figure this out for the last few hours now 🙁
The declaration in the controller.h is as follows-
NSMutableArray *imageSet;
UIImage *img, *img1, *img2, *img3, *img4, *img5;
The array is initialized in the controller –
-(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];
}
When the view appears this is what happens –
(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];
}
You are creating an
NSArray(non-mutable array) object here and assigning it to yourimageSetvariable. This is very bad becauseimageSetwas declared to be of typeNSMutableArray *, and the object you created has typeNSArray, andNSArrayis not a subtype ofNSMutableArray.So the error occurs because the object is actually an
NSArrayobject, notNSMutableArray(or subclass thereof), and therefore does not support areplaceObjectAtIndex:withObject:message.You should create an
NSMutableArrayobject instead: