My app crashes when I set the image-property on a UIImageView three times in a row (sometimes two times is enough). A few times I’ve seen a memory warning before the app closes, but most of the times it just collapses. The app does not crash in the simulator, so I’m quite sure it is a memory problem.
Here’s the code I use when setting the image property:
-(void)changeBgPictureTo:(UIImage *)img
{
[self.backgroundImage setImage:img];
}
The UIImages is allocated with the [UIImage imageWithData:] method:
[UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:type]]];
The image is set correctly the first two times, but crashes on the third time. It has nothing to do with a specific image file. I’ve tried with 10 different images and it makes no difference.
How do I make the UIImageView unload previous loaded images?
EDIT:
Okay, I’ve been asked for the whole code so here it goes:
I’m working with a class which looks like this:
@interface MyImage : NSObject
{
UIImage* image;
int imgId;
NSArray* colors; //contains 'UIColor' objects.
}
@property (nonatomic, retain) UIImage* image;
@property (nonatomic, retain) NSArray* colors;
@property (nonatomic, readwrite) int imgId;
-(id)initWithFileName:(NSString*)fileName withType:(NSString*)type andId:(int)imgId andColors:(NSArray*)colorArray;
@end
Here is the init implementation:
-(id)initWithFileName:(NSString*)fileName withType:(NSString*)type andId:(int)imageId andColors:(NSArray*)colorArray
{
self = [super init];
if (self)
{
self.colors = [NSArray arrayWithArray:colorArray];
self.imgId = imageId;
self.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:type]]];
}
return self;
}
I have a datacontroller which has a list of ‘MyImage’ objects which is added in a loop with this call:
[self.myImages addObject:[[MyImage alloc] initWithFileName:[NSString stringWithFormat:@"0000%d", i] withType:@"jpg" andId:i andColors:colors]];
I have 9 images which is named 00001.jpg, 00002.jpg, ….., 00008.jpg.
This data controller has a method like this:
-(MyImage *)getImageWithId:(int)imgId
{
for (MyImage* img in self.myImages)
{
if (img.imgId == imgId)
return img;
}
return nil;
}
The getImageWithId method is called like this:
-(void)btnPushed:(id)sender
{
[self.delegate changeBgPictureTo:[self.imgDataController getImageWithId:((UIButton*)sender).tag]];
}
The changeBgPictureTo method is the method which makes the setting of the image-property:
-(void)changeBgPictureTo:(MyImage *)img
{
NSLog(@"Setting image: %d", img.imgId);
[self.backgroundImage setImage:img.image];
}
The log prints “Setting image: 0000X:” three times, but crashes shortly after the third print.
Instead of storing the UIImage object inside MyObject class,try storing only the filename of the file.
and implementation
then in function