Skip to content

Instantly share code, notes, and snippets.

@maxhuk
Created April 8, 2013 11:41
Show Gist options
  • Save maxhuk/5336214 to your computer and use it in GitHub Desktop.
Save maxhuk/5336214 to your computer and use it in GitHub Desktop.
A simple way to create or schedule a timer that doesn't retain its target.
//
// NSTimer+WeakTarget.h
//
// Created by Maksym Huk on 4/8/13.
// Copyright (c) 2013 Maksym Huk. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSTimer (WeakTarget)
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
@end
//
// NSTimer+WeakTarget.m
//
// Created by Maksym Huk on 4/8/13.
// Copyright (c) 2013 Maksym Huk. All rights reserved.
//
#import "NSTimer+WeakTarget.h"
@interface WeakTimerTarget : NSObject
@property (weak, nonatomic) id target;
@property (nonatomic) SEL action;
- (id)initWithTarget:(id)target action:(SEL)action;
- (void)action:(id)sender;
@end
@implementation WeakTimerTarget
- (id)initWithTarget:(id)target action:(SEL)action
{
if (self = [super init]) {
self.target = target;
self.action = action;
}
return self;
}
- (void)action:(id)sender;
{
[_target performSelector:_action withObject:sender];
}
@end
@implementation NSTimer (WeakTarget)
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo
{
return [self timerWithTimeInterval:ti target:[[WeakTimerTarget alloc] initWithTarget:aTarget action:aSelector] selector:@selector(action:) userInfo:userInfo repeats:yesOrNo];
}
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo
{
return [self scheduledTimerWithTimeInterval:ti target:[[WeakTimerTarget alloc] initWithTarget:aTarget action:aSelector] selector:@selector(action:) userInfo:userInfo repeats:yesOrNo];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment