定时器的三种初始化方法

定时器的三种初始化方法:

1.

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

初始化完成后马上执行

2.

// 使用timerWithTimeInterval方法来实例化一个NSTimer,这时候NSTimer是不会启动的

self.paintingTimer = [NSTimer timerWithTimeInterval:1.0

                                                 target:self

                                               selector:@selector(paint:)

                                               userInfo:nil

                                                repeats:YES];



// 当需要调用时,可以把计时器添加到事件处理循环中

 [[NSRunLoop currentRunLoop] addTimer:self.paintingTimer forMode:NSDefaultRunLoopMode];

忽然想问一句:NSRunLoop是什么?

循环运行!就像是程序的中枢神经,一直在运转着,并且监视着程序各种的事件、线程等等。

一旦出现了相关的事件,那么就开始调度,分配适当的对象来执行适当的操作!

3.

- (void) startPainting{

    // 定义将调用的方法

    SEL selectorToCall = @selector(paint:);

    // SEL进行 方法签名

    NSMethodSignature *methodSignature =[[self class] instanceMethodSignatureForSelector:selectorToCall];

    // 初始化NSInvocation

    NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:methodSignature];

    [invocation setTarget:self];

    [invocation setSelector:selectorToCall];

    self.paintingTimer = [NSTimer timerWithTimeInterval:1.0

                                             invocation:invocation

                                                repeats:YES];

    

// 当需要调用时,可以把计时器添加到事件处理循环中

    [[NSRunLoop currentRunLoop] addTimer:self.paintingTimer forMode:NSDefaultRunLoopMode];

}


忽然想问一句:NSInvocation是什么?

Object-C 中的消息传递着。它可以以方法签名的方式来封装一个对象的方法,并且在各个对象中传送!主要可以用在NSTimer中。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值