Skip to content

Instantly share code, notes, and snippets.

@bendytree
Created May 29, 2013 23:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bendytree/5674709 to your computer and use it in GitHub Desktop.
Save bendytree/5674709 to your computer and use it in GitHub Desktop.
A starting point for an NSTimer that has a weak reference to its target. ARC only.
//
// NSWeakTimer.m
#import "NSWeakTimer.h"
@interface NSWeakTimerTarget : NSObject
@property (assign) id target;
@property (assign) SEL selector;
@property (assign) NSTimer* timer;
@end
@implementation NSWeakTimerTarget
- (void) fire
{
if(self.target)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self.target performSelector:self.selector withObject:nil];
#pragma clang diagnostic pop
}
else
{
[self.timer invalidate];
}
}
@end
@implementation NSWeakTimer
+ (NSTimer *) scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo
{
NSWeakTimerTarget* timerTarget = [[NSWeakTimerTarget alloc] init];
timerTarget.target = aTarget;
timerTarget.selector = aSelector;
timerTarget.timer = [NSTimer scheduledTimerWithTimeInterval:ti target:timerTarget selector:@selector(fire) userInfo:userInfo repeats:yesOrNo];
return timerTarget.timer;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment