Frage

I have a CGPoint declared in a UIView class, in my viewController I try to check if that CGPoint is not equal to CGPointZero, but I get this error:Invalid operands to binary expression ('CGPoint' (aka 'struct CGPoint') and 'CGPoint')

This is the if-statement:

if (joystick.velocity != CGPointZero)

The error points to the != and I dont know why it gives me an error.

joystick is the UIView class, CGPoint velocity is declared like this:

@property(nonatomic) CGPoint velocity;

War es hilfreich?

Lösung

Try this:

if (!CGPointEqualToPoint(joystick.velocity, CGPointZero))

Explanation: A CGPoint is actually a struct. The binary operand ("==" or "!=") it's only used to compare primitive values, usually useful to compare pointers, which in fact are integers representing a memory position.

As you have a struct, and not a reference to something, you would have to compare each value inside your struct, but fortunately apple already implemented a macro that performs this for you in the case of CGPoint.

If you are curious, you can command-click the macro above and see the implementation:

__CGPointEqualToPoint(CGPoint point1, CGPoint point2)
{
  return point1.x == point2.x && point1.y == point2.y;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top