【发布时间】:2014-04-29 21:56:15
【问题描述】:
在我的应用程序中,我将NSTimer 与传递给方法的块相关联;该块也被添加到一个块数组中。当计时器触发时,它的关联块被调用并且应该从数组中删除。所以我的设置如下所示:
@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
我的问题是当timerFired: 被调用时,块(有时)没有被删除。为什么?
【问题讨论】:
-
出于好奇,您为什么要保存块的副本?在示例中,您没有将其用于任何用途。
标签: ios objective-c macos objective-c-blocks