开始接触IOS的时候,object-C中的UIImageView中可以利用animationImages来实现序列动画,但是在实际应用时出问题了,触发的时候加载速度有点慢,在想办法解决加载速度的时候,偶然在别人的博客看到了NSTimer的用法,突来了想法。

   思路,利用NSTimer间隔的去替换UIImageView的image,这里先说下有关于image的imageWithContentsOfFile和imageNamed,开始我很乐意区使用imageNamed,因为不用写繁琐的代码,但是这是错误的,在很多论坛都有提及image的imageWithContentsOfFile和imageNamed对内存的问题,imageNamed会有缓存,而imageWithContentsOfFile是即用即清除,所以建议尽可能的要去自己使用imageWithContentsOfFile。

   代码


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize imageView;

NSTimer *timer;

int imageIndex;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];
    [self.view addSubview:imageView];

    imageIndex = 0;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}

- (void) changeImage{
    imageIndex += 1;
    NSString *imageName = [NSString stringWithFormat:@"飞兽%d",imageIndex];
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"];
    /*
     imageNamed:(NSString *)name;会产生缓存
     imageWithContentsOfFile:(NSString *)path;不会产生缓存
     */
    imageView.image = [UIImage imageWithContentsOfFile:imagePath];
    if (imageIndex == 20) {
        imageIndex = 0;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end