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

偶尔善良 提交于 2019-12-11 07:42:13

问题


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

回答1:


I think you want to use this method:

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

e.g.:

[theArray replaceObjectAtIndex:4 withObject:someOtherImage];



回答2:


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


来源:https://stackoverflow.com/questions/6005870/how-to-add-uiimages-to-an-nsmutablearray-and-change-the-images-later

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!