Home > AI > Uncategorized

RunLoop – 每隔4秒打印

- (void)runloopThread {
    printf("test \n");
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(runloopExample) object:nil];
    [thread start];
}




-(void) runloopExample {
    //1
    CFRunLoopRef r = CFRunLoopGetMain();
    
    //2: src
    CFRunLoopSourceRef src;
    CFRunLoopSourceContext srcCtx;

    bzero(&srcCtx, sizeof(srcCtx));
    srcCtx.perform = _perform;
    
    src = CFRunLoopSourceCreate(NULL, 0, &srcCtx);
    CFRunLoopAddSource(r, src, kCFRunLoopCommonModes);
    
    //3: timer
    CFRunLoopTimerRef timer;
    CFRunLoopTimerContext timerCtx;

    bzero(&timerCtx, sizeof(timerCtx));
    timerCtx.info = src;
    
    timer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), 4, 0, 0, _timer , &timerCtx);
    CFRunLoopAddTimer(r, timer, kCFRunLoopCommonModes);
    
    //4: run
    CFRunLoopRun();
    
    
}

static void _perform(void *info __unused) {
    printf("good \n");
    
}

static void _timer(CFRunLoopTimerRef timer __unused, void *info) {
    CFRunLoopSourceSignal(info);
}

 

运行 socket.runloopThread() (swift 运行oc,一个bridging header即可)

Related posts:

Leave a Reply