Created
April 8, 2013 11:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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