我显然知道如何使用NSTimers和cocos2d计时器,例如:
[self schedule: @selector(updater:) interval:0.5];
但所有这些计时器都调用了一个函数。我不想那样。
我需要一个计时器,在我的方法中将计数,最后,将执行一项操作,例如切换BOOL或更改整数。
有一种简单的方法可以在一行中完成吗?
非常感谢
答案 0 :(得分:2)
试试这个:
@interface CCScheduler (BlockAddition)
- (id)scheduleAfterDelay:(ccTime)delay block:(void(^)(ccTime dt))block;
@end
@interface NSObject (BlockAddition)
- (void)cc_invokeBlock:(ccTime)dt;
@end
@implementation NSObject (BlockAddition)
- (void)cc_invokeBlock:(ccTime)dt {
void(^block)(ccTime dt) = (id)self;
block(dt);
}
@end
@implementation CCScheduler (BlockAddition)
- (id)scheduleAfterDelay:(ccTime)delay block:(void(^)(ccTime dt))block {
block = [block copy];
[self scheduleSelector:@selector(cc_invokeBlock:) forTarget:block interval:0 paused:NO repeat:0 delay:delay];
return block;
}
@end
例如
[[CCDirector sharedDirector].scheduler scheduleAfterDelay:0.1 block:^(ccTime dt) {
NSLog("time's up");
}];
或者如果您使用的是旧版本的cocos2d
[[CCScheduler sharedScheduler] scheduleAfterDelay:0.1 block:^(ccTime dt) {
NSLog("time's up");
}];
答案 1 :(得分:1)
我不得不更改计划调用并取消计划,因此它不会被调用...就像这样:
#import "SchedulerBlock.h"
#import "cocos2d.h"
@implementation NSObject (BlockAddition)
- (void)cc_invokeBlock:(ccTime)dt {
void(^block)(ccTime dt) = (id)self;
block(dt);
[[CCScheduler sharedScheduler] unscheduleSelector:_cmd forTarget:block];
}
@end
@implementation CCScheduler (BlockAddition)
- (id)scheduleAfterDelay:(ccTime)delay block:(void(^)(ccTime dt))block {
block = [block copy];
[self scheduleSelector:@selector(cc_invokeBlock:) forTarget:block interval:delay paused:NO];
return block;
}
@end