thuai
8/14/2012 - 1:10 PM

RunLoop Observer

RunLoop Observer

#pragma mark - RunLoop Observer

- (void)onNewThread:(id)info
{
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    if (!runloop) {
        return ;
    }
    
    if (runloop == [NSRunLoop mainRunLoop]) {
        NSLog(@"Current runloop is the main runloop.\n");
    } else {
        NSLog(@"Current runloop is not the main runloop.\n");
    }
    
    NSString *currentMode = [runloop currentMode];
    if (currentMode) {
        NSLog(@"Limit date for %@ is %@.\n", currentMode, [runloop limitDateForMode:currentMode]);
    }
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(onTimerFired:) userInfo:nil repeats:NO];
    [runloop addTimer:timer forMode:NSRunLoopCommonModes];
    
    CFRunLoopObserverContext context = {
        0,
        self,
        NULL,
        NULL,
        NULL
    };
    
    CFRunLoopObserverRef observerRef = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &runloopObserverCallback, &context);
    CFRunLoopAddObserver([runloop getCFRunLoop], observerRef, kCFRunLoopCommonModes);
    
    [runloop run];
    
    CFRunLoopRemoveObserver([runloop getCFRunLoop], observerRef, kCFRunLoopCommonModes);
    CFRelease(observerRef);
}

- (void)onTimerFired:(id)info
{
    // Log will be put when a TestObject instance is deallocated
    TestObject *testObject = [[TestObject alloc] autorelease];
    testObject = nil;
}

static void runloopObserverCallback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
{
    CFRunLoopActivity currentActivity = activity;
    switch (currentActivity) {
        case kCFRunLoopEntry:
            NSLog(@"kCFRunLoopEntry \n");
            break;
            
        case kCFRunLoopBeforeTimers:
            NSLog(@"kCFRunLoopBeforeTimers \n");
            break;
            
        case kCFRunLoopBeforeSources:
            NSLog(@"kCFRunLoopBeforeSources \n");
            break;
            
        case kCFRunLoopBeforeWaiting:
            NSLog(@"kCFRunLoopBeforeWaiting \n");
            break;
            
        case kCFRunLoopAfterWaiting:
            NSLog(@"kCFRunLoopAfterWaiting \n");
            break;
            
        case kCFRunLoopExit:
            NSLog(@"kCFRunLoopExit \n");
            break;
            
        default:
            NSLog(@"Activity not recognized!\n");
            break;
    }
}