如何在方法incrementCount:completion
中传递一个块以及它看起来是什么样子,以便在CounterClass中增加后返回属性self.count
?我不确定我在方法中定义块参数(void(^)(void))callback;
的方式是否正确,即它是否也有返回值?
的ViewController
[NSTimer scheduledTimerWithTimeInterval:3.0
target:self.counterClass
selector:@selector(incrementCount:completion:)
userInfo:nil
repeats:YES];
CounterClass
-(void)incrementCount:(NSTimer *)timer completion:(void(^)(void))callback;
{
self.count += 1;
}
答案 0 :(得分:3)
NSTimer
期望调用一个接受零个或一个参数的方法,如果有一个参数,它应该是定时器实例本身。
因此,你不能拥有一个带有2个参数的方法,其中一个是一个块。
相反,删除第二个参数,只需在方法实现中调用另一个方法或块。该块可以存储为该类的@property。
答案 1 :(得分:0)
您可以使用dispatch_after。
的ViewController:
[self.counterClass incrementCountWithCompletion:^{
// Your block code
NSLog(@"block code");
}];
CounterClass:
-(void)incrementCountWithCompletion:(void(^)(void))block;
{
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
dispatch_queue_t queue = dispatch_get_main_queue(); // Choose whatever queue is approapriate to you
//Beware of retain cycles and use weak self pattern appropriately
dispatch_after(delay, queue, ^{
self.count += 1;
block();
[self incrementCountWithCompletion:block];
});
}
答案 2 :(得分:-1)
您可以将块添加到userInfo
:
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self.counterClass selector:@selector(incrementCount:) userInfo:@{@"completion" : [yourBlock copy]} repeats:YES];
CounterClass
- (void)incrementCount:(NSTimer *)timer {
self.count += 1;
void (^completion)(void) = timer.userInfo[@"completion"];
}
有关在字典中存储块的更多信息:blocks in nsdictionary?