ccTouchesMoved多次向对象添加对象,即使if语句应该避免这种情况

时间:2011-12-08 14:14:47

标签: objective-c cocos2d-iphone

如果调用ccTouchesMoved函数,则必须将移动手指范围内的精灵添加到数组中。但只有ONCE。我得到的结果是它多次添加被触摸的精灵(因为当它移动到精灵的外部时,手指仍然在精灵上)。所以我把它封装成一个if语句,应该避免这种情况。但它不......我该怎么办?

-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

    CCSprite* realSprite = [self whichHexagonTouched:convertedLocation];

    NSNumber *hexTag = [NSNumber numberWithInt:realSprite.tag];

    // If the hexagon is not in the array and not nil, it should destroy it and add it to the array

    if(realSprite != nil && ![hexTags containsObject:hexTag]){
        [self destroyHexagon:realSprite];    
        [hexTags addObject:hexTag];

        NSLog(@"these are the hexTags %@", hexTags);
        } 


}

1 个答案:

答案 0 :(得分:0)

为什么不使用NSSet(或NSMutableSet)?除非您想保留将精灵添加到列表中的顺序,否则NSMutableSet更适合您的情况。您甚至不必检查精灵是否已添加到列表中,因为它是由NSMutableSet在内部完成的。此外,对containsObject:上的NSSet进行了优化,因为它使用了对象哈希值。