NSTimer with anonymous function / block?

前端 未结 9 2339
囚心锁ツ
囚心锁ツ 2020-12-25 10:17

I want to be able to schedule three small events in the future without having to write a function for each. How can I do this using NSTimer? I understand block

9条回答
  •  执笔经年
    2020-12-25 10:48

    I've made a Macro that will do this and auto handle dealloc, arc, retain cycles etc. No need to worry about using weak references. It will also always be on main thread

    #define inlineTimer(__interval, __block) {\
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), (__block));\
    [NSTimer scheduledTimerWithTimeInterval:__interval repeats:YES block:^(NSTimer *__timer) {\
    if (self.window != nil) {\
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), (__block));\
    } else {\
    [__timer invalidate];\
    }\
    }];\
    }
    

    Example usage:

    __block ticks = 0;
    
    inlineTimer(0.5, ^{
        ticks++;
        self.label.text = [NSString stringWithFormat:@"Ticks: %i", ticks];//strong reference to self and self.label won't cause retain cycle! Wahoo
    });
    

    Note that self.label is not a weak reference, yet this will all be automatically released due to how the macro is structured.

    Naturally this only works w/ UI classes, given that it's checking .window for when it should dealloc.

提交回复
热议问题