Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer with block -- am I doing it right?

The following is my Objective-C category on NSTimer to do block-based firing of NSTimers. I can't see anything wrong with it, but what I am getting is that the block I pass into the schedule... method is being deallocated despite me calling copy on it.

What am I missing?

typedef void(^NSTimerFiredBlock)(NSTimer *timer);

@implementation NSTimer (MyExtension)

+ (void)timerFired:(NSTimer *)timer 
{
    NSTimerFiredBlock blk = timer.userInfo;
    if (blk != nil) {
        blk(timer);
    }
}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds 
                                    repeats:(BOOL)repeats 
                                   callback:(NSTimerFiredBlock)blk 
{
    return [NSTimer scheduledTimerWithTimeInterval:seconds
                                            target:self
                                          selector:@selector(timerFired:)
                                          userInfo:[blk copy]
                                           repeats:repeats];
}

@end
like image 504
user1175914 Avatar asked Feb 23 '12 02:02

user1175914


2 Answers

I found this code over at http://orion98mc.blogspot.ca/2012/08/objective-c-blocks-for-fun.html

Great work

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7
      target:[NSBlockOperation blockOperationWithBlock:^{ /* do this! */ }]
      selector:@selector(main)
      userInfo:nil
      repeats:NO
];
like image 182
Mc.Stever Avatar answered Oct 06 '22 08:10

Mc.Stever


You have a project on github that does the job !

Cocoapod BlocksKit, allow you to Blockify a bunch of Classes...

#import "NSTimer+BlocksKit.h"
[NSTimer bk_scheduledTimerWithTimeInterval:1.0 block:^(NSTimer *time) {
       // your code
    } repeats:YES];
like image 20
Nicolas Henin Avatar answered Oct 06 '22 07:10

Nicolas Henin