I'm developing an app and I need to verify if a given variable has the same value for a given time. How can I do it? Maybe a solution can be to use a thread and manually force this to test my variable each 100 millisecond (with the equivalent of the C function "wait" or something like that). Is it correct? I think (and hope) there's a more elegant solution.
Specifically, I'm working with beacons and I need to trigger a method when a beacon is immediate to my device for an amount of time.
When ranging CLBeacons
, you get a callback from the operating system every second anyway, so it may be easier to simply put your logic inside this callback method. Like this:
NSMutableDictionary *immediateRangeBeaconTimes;
...
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)iBeacons inRegion:(CLBeaconRegion *)region {
NSDate *now = [NSDate new];
for (CLBeacon *iBeacon in iBeacons) {
NSString *key = [NSString stringWithFormat:@"%@ %@ %@", iBeacon.proximityUUID, iBeacon.major, iBeacon.minor];
if ([immediateRangeBeaconTimes objectForKey:key] == Nil) {
if (iBeacon.proximity == CLProximityImmediate) {
[immediateRangeBeaconTimes setObject: now forKey:key];
}
}
else {
if (iBeacon.proximity == CLProximityImmediate) {
if ([now timeIntervalSinceDate: [immediateRangeBeaconTimes objectForKey:key]] > 60) {
NSLog(@"This beacon has been immediate for 60 seconds. Do something.");
}
}
else {
[immediateRangeBeaconTimes removeObjectForKey:key];
}
}
}
}
I realize this is not exactly what you were asking, but wanted to offer an alternative in case it works better for your use case.