TOM猫

来源:互联网 发布:上海程序员招聘网站 编辑:程序博客网 时间:2024/06/11 03:44


===

#import "CHViewController.h"@interface CHViewController ()@end@implementation CHViewController- (void)viewDidLoad{    [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.}- (void) playAnimation:(int)count filename:(NSString *)filename{    //创建可变数组    NSMutableArray *imagesArray = [[NSMutableArray alloc] init];    //添加图片    /*加载图片缓存问题:     1.有缓存(无法释放,参数传的是文件名)     [UIImage imageNamed:@""];//经常使用的可以用这个方法     2.无缓存(用完就会释放,参数传的是全路径)     [[UIImage alloc] initWithContentsOfFile:path];//占用内存大的不经常使用的用这个     */    for(int i=0;i<count;i++){        NSString *name = [NSString stringWithFormat:@"%@_%02d.jpg",filename,i];//        UIImage *image = [UIImage imageNamed:name];//有缓存        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:nil];        UIImage *img = [[UIImage alloc] initWithContentsOfFile:path];//无缓存        [imagesArray addObject:img];    }    //动画效果    _tom.animationImages = imagesArray;    _tom.animationDuration = 0.1 * count;    _tom.animationRepeatCount = 1;    [_tom startAnimating];}    //找到配置文件tom.plist的路径- (IBAction)btnClick:(UIButton *)sender {    NSBundle *bundle = [NSBundle mainBundle];    NSString *path = [bundle pathForResource:@"tom" ofType:@"plist"];    //根据文件路径加载字典    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];    //获取按钮中的title值    NSString * title = [sender titleForState:UIControlStateNormal];    //获取字典中事件对应的图片count    int count = [dict[title] intValue];    NSLog(@"%@-%d",title,count);    [self playAnimation:count filename:title];}@end


上次写的程序,发现在模拟器中运行后,内存一直保持在好几百兆,这样一旦在手机上运行,肯定卡退

所以这里我通过懒加载和清楚内存操作实现内存控制:

第一处:类似与单例模式,只能创建一次

- (void)playTom:(UIButton *)play{    if([_tom isAnimating]) return;//必须等待一个事件完成后才能下一个事件
第二处:这里右两种方式

- (void)playAnimation:(int)count fileName:(NSString *)fileName{    NSMutableArray *imagesArray = [[NSMutableArray alloc] init];    for(int i = 0;i < count;i++){        NSString *name = [NSString stringWithFormat:@"%@_%02d.jpg",fileName,i];        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:nil];        UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];        [imagesArray addObject:image];    }    _tom.animationImages = imagesArray;    _tom.animationDuration = 0.1*count;    _tom.animationRepeatCount = 1;    [_tom startAnimating];    //实现动画完成就清空图片所占内存    //[_tom performSelector:@selector(clearTom) withObject:nil afterDelay:_tom.animationDuration];    [_tom performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:_tom.animationDuration];}- (void)clearTom{    _tom.animationImages = nil;}

通过内存分析,可以看出来确实能实现一个功能之后的内存清空:



0 0
原创粉丝点击