定时器的三种初始化方法

来源:互联网 发布:淘宝怎么修改送货时间 编辑:程序博客网 时间:2024/06/01 16:01

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

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];



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

 [[NSRunLoopcurrentRunLoop]addTimer:self.paintingTimerforMode: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.paintingTimerforMode:NSDefaultRunLoopMode];

}


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

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

0 0
原创粉丝点击