In my app, I associate an NSTimer
with a block passed to a method; the block is also added to a an array of blocks. When the timer fires, its associated block is called and should be removed from the array. So my setup looks like this:
@interface MyObject : NSObject
@property(strong, nonatomic) NSMutableArray *allBlocks;
- (void)myMethodWithBlock:(void(^)(void))block;
- (void)timerFired:(NSTimer *)timer;
@end
@implementation MyObject
- (id)init
{
self = [super init];
if (self)
{
self.allBlocks = [NSMutableArray array];
}
return self;
}
- (void)myMethodWithBlock:(void(^)(void))block
{
[NSTimer scheduledTimerWithTimeInterval:5.0f
target:self
selector:@selector(timerFired:)
userInfo:block
repeats:NO];
[self.allBlocks addObject:block];
}
- (void)timerFired:(NSTimer *)timer
{
void(^block)(void) = timer.userInfo;
[self.allBlocks removeObject:block];
block();
}
@end
My problem is that when timerFired:
is called, the block is (sometimes) not removed. Why?