西贝了爷  

一:NSTimer

当时间间隔>1s是用NSTimer;

方法:

 [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];

 

关于内存释放

  如果我们启动了一个定时器,在某个界面释放前,将这个定时器停止,甚至置为nil,都不能是这个界面释放,原因是系统的循环池中还保有这个对象。所以我们需要这样做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-(void)dealloc{
    NSLog(@"dealloc:%@",[self class]);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    timer= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myLog:) userInfo:nil repeats:YES];
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    btn.backgroundColor=[UIColor redColor];
    [btn addTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
-(void)btn{
    if (timer.isValid) {
        [timer invalidate];
    }
    timer=nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}

在官方文档中我们可以看到 [timer invalidate]   timer=nil;是唯一的方法将定时器从循环池中移除。

雪花定时器

- (void)awakeFromNib

{

    // 添加定时器 0.1  0.35

   //    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];

   // 一般如果定时器调用频率非常高,<1s,通常不会使用NSTimer,NSTimer调用优先级不高,NSTimer在重绘的时候也不要使用

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)];

        [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

}

 

//- (void)timeChange

//{

//    // setNeedsDisplay 这个方法并不会马上调用 drawRect方法,仅仅是给当前视图做一个重绘标记,当下一次屏幕刷新的时候就会调用drawRect方法

//    [self setNeedsDisplay];

//}

 

static int _snowY = 0;

 

- (void)drawRect:(CGRect)rect {

    // Drawing code

   UIImage *image = [UIImage imageNamed:@"雪花"];

    [image drawAtPoint:CGPointMake(50, _snowY)];

     _snowY += 10;

     if (_snowY > rect.size.height) {

        _snowY = 0;

    } 

}

 

 

二:时间段.--计算一段代码的效率

    1s = 1000ms = 10^3ms(毫秒) = 10^6μs (微秒) = 10^9ns (纳秒) = 10^12ps (皮秒) = 10^15fs (飞秒)

    //当前时间:
    double date_s = CFAbsoluteTimeGetCurrent();for (int i = 0; i <1000; i++) {
        NSLog(@"I Love You!!!");
    }
    //时间差.
    double date_current = CFAbsoluteTimeGetCurrent() - date_s;
    NSLog(@" ForLoop Time: %f ms",date_current * 1000);

 

 

 

  

posted on 2016-04-17 20:05  西贝了爷  阅读(374)  评论(0编辑  收藏  举报