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;
}
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;
}