1

我想尝试使用块来相对于某些输入事件更新实例变量。

在我的 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);  
}

我尝试了几件事,但是当我使用 self 实例时我有一个 BAD_ACCESS 。我不明白问题出在哪里。

4

1 回答 1

1

您需要复制块:

- (id)init {
    if (self = [super init]) {
        touchCallback = [^(NSSet* set){
            UITouch * touch= [set anyObject];
            self.touchPoint = [touch locationInView:self.view];
        } copy];
    }
    return self;
}

这是因为该块是在堆栈上创建的,如果您想稍后使用它,您需要制作一个副本以将其复制到堆中。(该块将在 if 语句范围的末尾“消失”)

于 2012-10-26T16:21:11.003 回答