[objective-c]在 NSArray 中存储 UITouch

标签: ios Objective-C
发布时间: 2016/10/2 13:06:07
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试图在字典或数组中存储 UITouches,遇到一些问题。存储 CGPoints 作品很好,但不是存储 UITouches。

进一步解释︰ 触动我到底想向输出数组时初始化数组时接触开始,存储在数组中,每个 UITouch。我一直在寻找一些时间,但我还没有找到任何示例代码来执行此操作。

NSMutableArray *touchesArray;
NSMutableArray *pointArray;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    touchesArray = [[NSMutableArray alloc] init];

    pointArray = [[NSMutableArray alloc] init];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];
     [pointArray addObject:[NSValue valueWithCGPoint: currentPoint]];

    [touchesArray addObject:[NSValue valueWithPointer:(__bridge const void *)(touch)]];

    for (UITouch *touch in touches)
    {
        NSLog(@"x location %f",[touch locationInView:self].x);
    }


}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{        

    for (UITouch *touch in touches)
    {        
        NSLog(@"%f",[touch locationInView:self].x);
    }

    for(id p in pointArray){
        NSValue *val = p;
        CGPoint point = [val CGPointValue];
        NSLog(@"%f",point.x);
    }

    //ERROR!
    for(id p in touchesArray){
        NSValue *val = p;
        UITouch *t = (UITouch*) p;
        NSLog(@"%@",[t timestamp]);
    }

}

解决方法 1:

使用一个包装对象为我工作。UITouch 总是指向相同的地址。

#import "TouchInfo.h"

@implementation TouchInfo

@synthesize timestamp;
@synthesize location;

@end


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
int ns = [touches count];
NSLog(@"number of touches  %i",ns);
for(UITouch *touch in touches)
{
    NSNumber *val = [NSNumber numberWithFloat:[touch timestamp]];        
    TouchInfo *touchInfo = [[TouchInfo alloc] init];
    touchInfo.location = [touch locationInView:self];
    touchInfo.timestamp = [touch timestamp];
}
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

int nt = [touchesArray count];
for (int i = 0; i < nt; i++){
    TouchInfo *touchInfo = (TouchInfo*)[touchesArray objectAtIndex:i];
    NSLog(@"%f  %f   %f",touchInfo.timestamp,touchInfo.location.x,touchInfo.location.y);    

}
}
赞助商