Skip to content

Instantly share code, notes, and snippets.

@AlvaroFranco
Last active December 16, 2024 07:09
Show Gist options
  • Select an option

  • Save AlvaroFranco/11284510 to your computer and use it in GitHub Desktop.

Select an option

Save AlvaroFranco/11284510 to your computer and use it in GitHub Desktop.
NSTimer extension with block support and the ability to pause and resume it
//
// NSTimer+Extension.h
// NSTimer+Extension
//
// Created by Alvaro Franco on 4/25/14.
// Copyright (c) 2014 AlvaroFranco. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSTimer (Extension)
+(id)scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats;
+(id)timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats;
-(void)pauseTimer;
-(void)resumeTimer;
@end
//
// NSTimer+Extension.m
// NSTimer+Extension
//
// Created by Alvaro Franco on 4/25/14.
// Copyright (c) 2014 AlvaroFranco. All rights reserved.
//
#import "NSTimer+Extension.h"
#import <objc/runtime.h>
@implementation NSTimer (Extension)
+(id)scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats {
void (^block)() = [inBlock copy];
id ret = [self scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(executeSimpleBlock:) userInfo:block repeats:inRepeats];
return ret;
}
+(id)timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats {
void (^block)() = [inBlock copy];
id ret = [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(executeSimpleBlock:) userInfo:block repeats:inRepeats];
return ret;
}
+(void)executeSimpleBlock:(NSTimer *)inTimer {
if([inTimer userInfo]) {
void (^block)() = (void (^)())[inTimer userInfo];
block();
}
}
static NSString *const NSTimerPauseDate = @"NSTimerPauseDate";
static NSString *const NSTimerPreviousFireDate = @"NSTimerPreviousFireDate";
-(void)pauseTimer {
objc_setAssociatedObject(self, (__bridge const void *)(NSTimerPauseDate), [NSDate date], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(self, (__bridge const void *)(NSTimerPreviousFireDate), self.fireDate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.fireDate = [NSDate distantFuture];
}
-(void)resumeTimer {
NSDate *pauseDate = objc_getAssociatedObject(self, (__bridge const void *)NSTimerPauseDate);
NSDate *previousFireDate = objc_getAssociatedObject(self, (__bridge const void *)NSTimerPreviousFireDate);
const NSTimeInterval pauseTime = -[pauseDate timeIntervalSinceNow];
self.fireDate = [NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate];
}
@end
@hewigovens
Copy link
Copy Markdown

Line:9 should be NSTimer+Extension.h

@syrakozz
Copy link
Copy Markdown

could you plz write how we can use it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment