我研究了数百篇帖子,但仍然无法弄清楚我的问题出在哪里。我有一组图像名称,我正在尝试随机选择一个图像并更新事件的 ImageView 。在我的设备上运行时,它会在 12-15 个图像后崩溃。
- (void)viewDidLoad
{
[super viewDidLoad];
self.predictionArray = [[NSArray alloc] initWithObjects:@"IMG_0006.JPG",
@"IMG_0007.JPG",
@"IMG_0008.JPG",
@"IMG_0034.jpg",
@"IMG_0036.jpg",
@"IMG_0043.jpg",
@"IMG_0062.JPG",
@"IMG_0069.JPG",
@"IMG_0076.jpg",
@"IMG_0093.jpg",
@"IMG_0096.jpg",
@"IMG_0168.jpg",
@"IMG_0240.jpg",
@"IMG_0251.jpg",
@"IMG_0262.jpg",
@"IMG_0264.jpg",
@"IMG_0310.jpg",
@"IMG_0351.jpg",
@"IMG_0355.jpg",
@"IMG_0391.jpg",
@"IMG_0404.jpg",
@"IMG_0417.jpg",
@"IMG_0428.jpg",
@"IMG_0461.jpg",
@"IMG_0471.jpg",
@"IMG_0485.jpg",
@"IMG_0492.jpg",
@"IMG_0550.jpg",
@"IMG_0568.jpg",
@"IMG_0822.jpg", nil];
[self makePrediction];
}
- (void) makePrediction {
NSUInteger index = arc4random_uniform(self.predictionArray.count);
[self.pageImage setImage:[UIImage imageNamed:[self.predictionArray objectAtIndex:index ]]];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self makePrediction];
}
最佳答案
您正在使用 imageNamed: 方法来设置 imageview 的图像。但问题是 imageNamed: 方法有自己的缓存机制,您无法控制因此,我们不知道分配的内存何时何地被释放。因此,不要使用 imageNamed: 方法,而是使用以下方法来设置图像。
NSString* imgpath= [ [ NSBundle mainBundle] pathForResource:@"sample" ofType:@"png"];
imgviw.image = [ UIImage imageWithContentsOfFile: imgPath];
使用 imageWithContentsOfFile: 方法的主要优点是该方法不会缓存图像,因此不会因保留大图像而导致任何内存问题。另外,在将图像应用于 imageview 之前,您可以设置 imgviw.image = nil
然后设置图像以避免内存泄漏问题
关于ios - 更新 UIImageView 会导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14531322/