我想尝试使用块相对更新一个实例变量,以更新某些输入事件。
在我的UiviewController类中:
@interface ViewController : UIViewController{
CGPoint touchPoint;
void (^touchCallback)(NSSet* touches);
}
@property(readwrite) CGPoint touchPoint;
@end
在实现文件中:
-(id) init{
if (self = [super init]){
touchCallback = ^(NSSet* set){
UITouch * touch= [set anyObject];
self.touchPoint = [touch locationInView:self.view];
};
}
return self;
}
在回调函数中我使用块:
-(void)touchesBegin:(NSSet *)touches withEvent:(UIEvent *)event{
touchCallback(touches);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
touchCallback(touches);
}
我尝试了几件事,但是当我使用自我实例时,我有一个bad_access。我不明白问题在哪里。
您需要复制块:
- (id)init {
if (self = [super init]) {
touchCallback = [^(NSSet* set){
UITouch * touch= [set anyObject];
self.touchPoint = [touch locationInView:self.view];
} copy];
}
return self;
}
这是因为该块是在堆栈上创建的,如果您想以后使用它,则需要制作副本将其复制到堆中。(该块将在命令范围的末端"走开")