场景: 在需要执行一个图片组动画时,如何保证动画结束后,图片从内存中消失
涉及到的核心方法:
imageWithContentsOfFile:imageNamed:
总结:
// 设置animationImages为空后: // 通过imageWithContentsOfFile:加载的图片数组会从内存中消失 - 适用于使用频次较低、大量的图片 // 通过imageNamed:方式加载的图片会持续保留在内存中(使用后在内存中有缓存) - 适用于经常使用,内存占用较小的图片的加载方式;放到Assets.xcassets的图片,默认就有缓存。
Demo:
#import "ViewController.h"@interface ViewController ()@property (nonatomic, strong) UIImageView *imageView;@end@implementation ViewController- (UIImageView *)imageView{if (!_imageView) {_imageView = [UIImageView new];_imageView.backgroundColor = [UIColor darkGrayColor];_imageView.contentMode = UIViewContentModeScaleAspectFit;}return _imageView;}- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.[self.view addSubview:self.imageView];self.imageView.frame = CGRectInset(self.view.bounds, 10, 80);UIStackView *stackView = [[UIStackView alloc] initWithFrame:CGRectMake(0, 40, 300, 40)];stackView.axis = UILayoutConstraintAxisHorizontal;stackView.distribution = UIStackViewDistributionFillEqually;[self.view addSubview:stackView];stackView.backgroundColor = [UIColor grayColor];{UIButton *btn1 = [UIButton new];[btn1 setTitle:@"开始1" forState:UIControlStateNormal];[btn1 addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];[stackView addArrangedSubview:btn1];}{UIButton *btn1 = [UIButton new];[btn1 setTitle:@"开始2" forState:UIControlStateNormal];[btn1 addTarget:self action:@selector(start2:) forControlEvents:UIControlEventTouchUpInside];[stackView addArrangedSubview:btn1];}{UIButton *btn1 = [UIButton new];[btn1 setTitle:@"结束" forState:UIControlStateNormal];[btn1 addTarget:self action:@selector(end:) forControlEvents:UIControlEventTouchUpInside];[stackView addArrangedSubview:btn1];}}- (void)start:(UIButton *)sender{NSMutableArray *images = [NSMutableArray array];for (NSInteger i = 0; i<8; i++) {NSString *fileName = [NSString stringWithFormat:@"moto_%03ld",i];NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"jpeg"];[images addObject:[UIImage imageWithContentsOfFile:filePath]];}self.imageView.animationImages = images;self.imageView.animationDuration = 8;self.imageView.animationRepeatCount = 2;[self.imageView startAnimating];}- (void)start2:(UIButton *)sender{NSMutableArray *images = [NSMutableArray array];for (NSInteger i = 0; i<8; i++) {NSString *fileName = [NSString stringWithFormat:@"moto_%03ld",i];[images addObject:[UIImage imageNamed:fileName]];}self.imageView.animationImages = images;self.imageView.animationDuration = 8;self.imageView.animationRepeatCount = 2;[self.imageView startAnimating];}- (void)end:(UIButton *)sender{[self.imageView stopAnimating];// 设置animationImages为空后:// 通过imageWithContentsOfFile:加载的图片数组会从内存中消失 - 适用于使用频次较低、大量的图片// 通过imageNamed:方式加载的图片会持续保留在内存中(使用后在内存中有缓存) - 适用于经常使用,内存占用较小的图片的加载方式;放到Assets.xcassets的图片,默认就有缓存。self.imageView.animationImages = nil;}@end
