Skip to content

Instantly share code, notes, and snippets.

@alfwatt
Last active December 10, 2020 01:18
Show Gist options
  • Save alfwatt/e1fb9cf7d3ff52196e864284cf4c33fa to your computer and use it in GitHub Desktop.
Save alfwatt/e1fb9cf7d3ff52196e864284cf4c33fa to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@interface NSRunLoop (Condition)
-(BOOL)runInDefaultModeWhileCondition:(BOOL *)condition inIntervals:(NSTimeInterval) quantum;
-(BOOL)runWhileCondition:(BOOL *)condition inMode:(NSString *)mode inIntervals:(NSTimeInterval) quantum;
@end
#import "NSRunLoop+Condition.h"
@implementation NSRunLoop (Condition)
-(BOOL)runInDefaultModeWhileCondition:(BOOL *)condition inIntervals:(NSTimeInterval) quantum {
return [self runWhileCondition:condition inMode:NSDefaultRunLoopMode inIntervals:quantum];
}
-(BOOL)runWhileCondition:(BOOL *)condition inMode:(NSString *)mode inIntervals:(NSTimeInterval) quantum {
BOOL didRun = NO;
BOOL shouldRun = YES;
NSPort *dummyPort = [NSMachPort port];
[self addPort:dummyPort forMode:NSDefaultRunLoopMode];
while (shouldRun) {
@autoreleasepool {
didRun = [self runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:quantum]];
shouldRun = (didRun ? *condition : NO);
}
}
[self removePort:dummyPort forMode:NSDefaultRunLoopMode];
return didRun;
}
@end
@alfwatt
Copy link
Author

alfwatt commented Dec 10, 2020

This is BSD Licensed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment