【发布时间】:2011-09-09 10:11:41
【问题描述】:
在一些多点触控“在屏幕上绘图”代码的维护中,我遇到了一个关于如何在 touchesBegan:withEvent:、touchesMoved:withEvent: 和 touchesEnded:withEvent: 之间设置对触控实例的引用的错误。
代码使用一个NSDictionary实例在touchesBegan:withEvent:中存储touches的引用,如下:
for (UITouch *touch in touches]) {
NSValue *touchValue = [NSValue valueWithPointer:touch];
NSString *key = [NSString stringWithFormat:@"%@", touchValue];
[myTouches setValue:squiggle forKey:key];
}
并在 touchesEnded:withEvent: 中检索它们:
for (UITouch *touch in touches) {
NSValue *touchValue = [NSValue valueWithPointer:touch];
NSString *key = [NSString stringWithFormat:@"%@", touchValue];
NSObject *valueFromDictionary = [myTouches valueForKey:key];
[myTouches removeObjectForKey:key];
}
在最后一段代码中,valueFromDictionary 碰巧偶尔为 nil,因为字典不知道键。偶尔,我的意思是大约 1% 的时间。
现在上下文已经设置好了,我的问题是:
知道为什么这段代码有问题吗?我不确定为什么它不起作用,尤其是因为错误频率非常低
Some doc from Apple 表示使用 UITouch 对象的地址作为键是一个好主意
:但这意味着使用 NSValue* 对象而不是 NSString* 对象(并因此使用 CFDictionaryRef 而不是NSDictionary 因为 UITouch 没有实现复制协议)。为什么存储地址的 NSString 表示而不是 NSValue 本身不能成为能够使用 NSDictionary 的简单解决方案?更新:Apple 已更新页面并删除了存储示例通过 NSString 的 UITouch 并仅提及 not-object-at-all CFDictionaryRef 解决方案。
恐怕我离 C 和指针的东西还很远,需要帮助来理解这段代码中存在错误的原因。
【问题讨论】:
标签: ios pointers reference multi-touch touchesbegan