开发者

UITouch object behaving oddly

I wanted to get points where user is touching on the screen therefore I wrote following code which w开发者_如何学编程ill fire when user will touch somewhere on the screen

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [[UITouch alloc] init]; 
    touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    if (CGRectContainsPoint([dob frame], point)) {
        [self showDatePickerforDOB:YES];
    }
}

but this code is giving run time error. Upon debugging it was revealed that locationInView is not recognized as a function of touch object on the other hand it is documented in iphone class reference documentation. When I changed code to exclude alloc i.e UITouch *touch; touch = [touches anyObject]; then locationInView is perfectly working fine. Any ideas why UITouch *touch = [[UITouch alloc] init]; is giving runtime error.


I think you should not alloc and init the touch pointer, the correct code should be:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    CGPoint point  = [touch locationInView:self];

    if (CGRectContainsPoint([dob frame], point)) {
        [self showDatePickerforDOB:YES];
    }
}

[touches anyObject] will return an autorelease object so you don't need to alloc and init the touch pointer.


I got the reason why there was an error. It was because of line

CGPoint point = [touch locationInView:self];

when I changed it to CGPoint point = [touch locationInView:self.view]; runtime error was removed. The reason is that locationInView function takes UIView as its parameter and on the other hand i was giving it a delegate i.e 'self'.

so self.view solved the issue

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜