NSTimer Category + Blocks implementation to replace selector

后端 未结 3 682
清歌不尽
清歌不尽 2021-01-06 20:16

I am quite new to blocks and objective-c, and i am trying to write my first category using both. My idea is to create a category on NSTimer that will receive a block as a pa

3条回答
  •  鱼传尺愫
    2021-01-06 20:48

    What about leveraging userInfo to carry your block? (this is done with ARC)

    void (^callback)(void) = ^{
        NSLog(@"do stuff");
    }
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:10.0 target:self selector:@selector(handleTimeout:) userInfo:[NSDictionary dictionaryWithObject:[callback copy] forKey:@"block"] repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    

    And then add the static selector of:

    + (void)handleTimeout:(NSTimer *)timer
    {
        void (^callback)(void) = [timer.userInfo objectForKey:@"block"];
        callback();
    
        [timer invalidate];
        timer = nil;
    };
    

提交回复
热议问题