0
votes

I have 10 region. When I enter each of those region I create an object NSDate because when I will exit of those region I want to calculate the time that I spent in each of the region. My code is:

  • (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    self.dateEnteredRegion = [NSDate date]; }

  • (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region { NSTimeInterval timeInterval = fabs(round([self.dateEnteredRegion timeIntervalSinceNow])); NSLog(@"Exit from Region - %@. Time spent: %f", region.identifier, timeInterval); }

The problem is this: if the regions are very close, the method didEnterRegion for new region, triggered before the method didExitRegion for old region and the dateEnteredRegion is recreated. So, it will be not valid when I calculate the elapsed time in didExitRegion for old region. The regions are dynamically created and I do not know how many can be active at the time. Is it possible to create and bind to each region its own object NSDate? Thanks

1

1 Answers

0
votes

In some cases it is best to create your own class that holds the region and both dates and then create and insert these items into some array. In your case it might be simplest to use a NSDictionary holding those 3 data and put it into array:

NSMutableArray *regionCrossing = [[NSMutableArray alloc] init];        

static NSString *regionKey = @"region";
static NSString *dateEnteredKey = @"dateEntered";
static NSString *dateExitedKey = @"dateExited";
   //when got region:
NSMutableDictionary *regionData = [[NSMutableDictionary alloc] init];
CLRegion *region;
[regionData setObject:region forKey:regionKey];
[regionCrossing addObject:regionData];
   //when got enter date (do not set if nil)
NSDate *enteredDate;
[regionData setObject:enteredDate forKey:dateEnteredKey];
   //when got exit date (do not set if nil)
NSDate *exitDate;
[regionData setObject:exitDate forKey:dateExitedKey];
   //collect all data
for(NSDictionary *item in regionCrossing) {
        if(item[dateEnteredKey] != nil && item[dateExitedKey] != nil) {
                //this item has both dates already
        }
}

To get the correct region data from the array you will need to iterate and check item[regionKey] == currentRegion.