0

I have a cursor object and I want to be able to tell when it intersects an nsbutton, and whether it does continuously for a 3 seconds. My code works except that when the cursor comes near a button, it freezes until it has been three seconds and then logs "Button overlapped for 3 seconds".

   NSDate* date;
   -(BOOL)checkIfIntersects :(NSButton*)button {

      BOOL intersects =  CGRectIntersectsRect (cursor.frame,button.frame);

      if (intersects) {
         date = [NSDate date];

        while (intersects) {
            if ([date timeIntervalSinceNow] < -1)
            {
                NSLog(@"Button overlapped for 3 seconds");

                break;
            }
            intersects =  CGRectIntersectsRect (cursor.frame,button.frame);      
       }

    }

    return NO;

}
Paige DePol
  • 1,121
  • 1
  • 9
  • 23
user3247022
  • 69
  • 1
  • 9

1 Answers1

1

This is because your thread is stuck inside the while(intersects) loop, only exiting after the internal if statement is satisfied. This will hang your entire thread.

The quickest/easiest solution for you would be to have an interaction flag outside of your function along with your NSDate.

  NSDate* momentIntersectionBegan = nil;
  BOOL intersectedPreviously = false;

  -(BOOL)checkIfIntersects :(NSButton*)button {
     BOOL currentlyIntersects =  CGRectIntersectsRect (cursor.frame,button.frame);

  if (currentlyIntersects) {
    if(intersectedPreviously){
        if ([momentIntersectionBegan timeIntervalSinceNow] < -3)
        {
            NSLog(@"Button overlapped for 3 seconds");
        }
    }else{
        momentIntersected = [NSDate date];
    }
      intersectedPreviously = true;
  }else{
      intersectedPreviously = false;
  } 

return NO;

}
Andrew T.
  • 2,088
  • 1
  • 20
  • 42
  • Now it doesn't freeze, but "button overlapped" never happens – user3247022 Jan 29 '14 at 02:43
  • and don't I have to call checkIfIntersects at multiple times now since it's no longer a loop? – user3247022 Jan 29 '14 at 02:44
  • What the code I wrote above will do is keep track of the last time the button was intersected, if an intersection was detected during the previous call, and whether an intersection was consistently detected for three seconds. I wrote it assuming this method will be called every tick, like if it was being called from a repeating `NSTimer`, or inside a game loop. The best solution depends on your overall implementation. – Andrew T. Jan 29 '14 at 03:00