Ramiro
Ramiro

Reputation: 229

Objective C: Comparing CGPoints

I am trying to do an if-else statement for my CGPoints how would I be able to do that, I tried this code...

if (point1 != point2)
{
       //statement
}

I'm having this error

Invalid operand for binary expression...

Thanks!

Upvotes: 13

Views: 7834

Answers (4)

xhan
xhan

Reputation: 6287

Try to use function CGPointEqualToPoint instead.

if (!CGPointEqualToPoint(p1,p2))
{
  //statement
}

Upvotes: 46

Mike K
Mike K

Reputation: 2227

you can do:

if (!CGPointEqualToPoint(point1, point2)) {
....
}

floats (and therefore CGFloats) are a bit tricky because sometimes you want them to be considered equal, but they're a tiny margin off. if you want a "fuzzy" comparison, you could do something like:

if (fabsf(point1.x - point2.x) > 0.0001f || fabsf(point1.y - point2.y) > 0.0001f) {
...
}

this checks to see if the x & y components of point1 and point2 are different by an amount greater than 0.0001 (a totally arbitrary number, can be whatever you want depending on your desired accuracy).

Upvotes: 8

bryanmac
bryanmac

Reputation: 39296

see CGPointEqualToPoint: Returns whether two points are equal.

bool CGPointEqualToPoint (
   CGPoint point1,
   CGPoint point2
);

http://developer.apple.com/library/mac/#DOCUMENTATION/GraphicsImaging/Reference/CGGeometry/Reference/reference.html

Parameters

  • point1: The first point to examine.
  • point2: The second point to examine.

Return Value

true if the two specified points are the same; otherwise, false.

Upvotes: 5

Nekto
Nekto

Reputation: 17877

I would advice to use following function: (from Apple Docs)

CGPointEqualToPoint : Returns whether two points are equal.

bool CGPointEqualToPoint (CGPoint point1, CGPoint point2);

Parameters

point1 : The first point to examine.

point2 : The second point to examine.

Return Value true if the two specified points are the same; otherwise, false.

For more information read here: CGGeometry Reference

Upvotes: 7

Related Questions