[英]For loop variable always evaluating to true
烦人的新手问题在这里。 我一接触到该变量, isPlayerTouchingAnotherPlayer
这个变量设置为true。 我几乎肯定我知道为什么,但是我找不到在日志中显示此内容进行确认的方法。 我可以通过为每个对象设置不同的标志号来做到这一点,但我希望有另一种方法。
问题在于,该piece
也是一个位于p1Array
的对象,因此,一旦我触摸它,它就会自动击中,并且isPlayerTouchingAnotherPlayer
被评估为true。
有什么方法可以打印出以某种方式触摸的对象的视图或图像名称以确认这一点? 而且,有一种方法可以避免这种烦人的冲突。
for (int i = 0; i <[p1Array count]; i++) {
UIImageView *tempP1;
tempP1 =[p1Array objectAtIndex:i];
if (CGRectIntersectsRect(piece.frame, tempP1.frame)) {
NSLog(@"selected piece: %@, touched piece: %@ ", piece, tempP1);
isPlayerTouchingAnotherPlayer = TRUE;
}
}
为什么不使用快速枚举并跳过您不感兴趣的图像视图。
for (UIImageView *imageView in p1Array) {
if (imageView == piece)
continue;
if (CGRectIntersectsRect(imageView.frame, piece.frame)) {
// do whatever
}
}
似乎您已经在提供的代码示例中打印出了触摸对象的名称。 如果要打印对象的特定属性,可以执行此操作。
一旦我触摸它,它就会自动击中,并且isPlayerTouchingAnotherPlayer被评估为true。
然后,您应该获得一条日志消息,该消息显示所选零件和被触摸的零件的相同对象。 如果这是发生了什么,然后只需添加一个条件,你if
阻止它:
if (piece != tempP1 && CGRectIntersectsRect(piece.frame, tempP1.frame)) {
只是
NSLog(@"%@ %@", piece, tempP1);
要么
NSLog(@"%ld %ld", (NSInteger) piece, (NSInteger) tempP1);
第一个向您显示对象的描述,第二个向您显示内存中的地址,如果它是相同的地址,则它是相同的对象。
您可以通过简单的等价检查以排除同一对象来简单地检查它是否是同一对象(指针):
if (piece != tempP1) {
if (CGRectIntersectsRect(piece.frame, tempP1.frame)) {
...
}
此外,您想编写以下代码:
for ( int i = 0;
( ( i < [p1Array count] )
&& ( ! isPlayerTouchingAnotherPlayer )
);
i++
) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.