给CFRunLoop添加Timer

最近在学习NSThread的应用,既然学习了NSThread就免不了学习CFRunLoop。今天便学习了给Loop添加timer的方法。直接贴代码。

#import <CoreFoundation/CoreFoundation.h>

//#import "AppDelegate.h"


static void _timer(CFRunLoopTimerRef timer __unused, void *info)
{
   // CFRunLoopSourceSignal(info);
    (*(int *)(info))++;
    NSLog(@"%d",*(int *)info);
}


int main(int argc, char *argv[])
{
    @autoreleasepool {
        int i=0;
        CFRunLoopTimerRef timer;
        CFRunLoopTimerContext timer_context;
        
        bzero(&timer_context, sizeof(timer_context));
        timer_context.info = &i;
        timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent(), 1, 0, 0, _timer, &timer_context);
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);
        CFRunLoopRun();
        
       // returnUIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegateclass]));
    }
}

  最后的结果自然是:

2012-11-22 23:09:51.568 runloop[32118:707] 1

2012-11-22 23:09:52.568 runloop[32118:707] 2

2012-11-22 23:09:53.569 runloop[32118:707] 3

2012-11-22 23:09:54.569 runloop[32118:707] 4

2012-11-22 23:09:55.568 runloop[32118:707] 5

2012-11-22 23:09:56.569 runloop[32118:707] 6

2012-11-22 23:09:57.569 runloop[32118:707] 7

2012-11-22 23:09:58.568 runloop[32118:707] 8

2012-11-22 23:09:59.569 runloop[32118:707] 9

2012-11-22 23:10:00.569 runloop[32118:707] 10

变量i的值随这timer的增加二增加~~~希望对大家有所帮助!!!!

posted @ 2012-11-22 23:19  I_O_S  阅读(909)  评论(0编辑  收藏  举报