How to add UIImages to an NSMutableArray, and change the images later?

I am making a simple game that requires that I draw multiple UIImages in many different places. My problem here is that I need to add the UIImages to an NSMutableArray, and access them later. Using NSStrings to represent the images (such as for paths) will not work here, so I need to know how to change the images for every UIImage in the array.

My code is as follows (at least, for accessing the NSMutableArray). The NSMutableArray is declared in my .h file, and is initialized in a different method.

for (int a = 0; a <= [theArray count]; a ++) {
    // I make a UIImage, which I will draw later
    UIImage *theImage = [theArray objectAtIndex:a];
    // then I do the drawing
}

This works fine. My problem is that I cannot figure out how to change a particular object in the NSMutableArray. How can I do this?

By the way, I am adding the UIImages to the NSMutableArray with the following code.

+ (void) createCarWithImage:(NSString*)theImageName {
    UIImage *anImage= [UIImage imageNamed:theImageName];
    [theArray addObject:anImage];
}

Answers


I think you want to use this method:

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject

e.g.:

[theArray replaceObjectAtIndex:4 withObject:someOtherImage];

Just modify each UIImage in the NSMutableArray as is, you only have a pointer to the actual data. That is, regardless of what pointer you use to change the data, the data is changed for every pointer.

Additionally, you can also iterate over your UIImages with:

for (UIImage *img in theArray)
{
     //send messages to img
}

Answer to Comment

You can modify the UIImage at index 4 by:

UIImage *image = [theArray objectAtIndex:4];
//send messages to image

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.