Question

I need to get the final activeTime value once the loop has completed.

The code below runs a loop, which in turn calls a block many times (which runs an async process). Each loop will increment activeTime if more than 10 steps occurred in that period.

Ultimately I want to call this code and have it return the final value of activeTime.

I am thinking of completionhandler but am not sure.

Can someone advise how I may achieve this?

    __block NSInteger activeTime = 0;
    for (NSDate *date = [self startDateOfToday]; 
         [date compare:[NSDate date]] == NSOrderedAscending; 
         date = [date dateByAddingTimeInterval:10])        
    {
        NSDate *rangeStart = date;
        NSDate *rangeEnd = [date dateByAddingTimeInterval:10];

        [stepCounter queryStepCountStartingFrom:rangeStart
                                             to:rangeEnd
                                        toQueue:[NSOperationQueue mainQueue]
                                    withHandler:^(NSInteger numberOfSteps, NSError *error) {

                                        if (numberOfSteps > 10) {
                                            activeTime=activeTime+10;
                                        }

                                        NSLog(@"Steps = %ld; Time = %ld",(long)numberOfSteps, (long)activeTime);
                                    }];
    }
Was it helpful?

Solution

You could use a callback

- (void) myfunction {
    __block NSInteger activeTime = 0;
    for (NSDate *date = [self startDateOfToday]; 
         [date compare:[NSDate date]] == NSOrderedAscending; 
         date = [date dateByAddingTimeInterval:10])        
    {
        NSDate *rangeStart = date;
        NSDate *rangeEnd = [date dateByAddingTimeInterval:10];

        [stepCounter queryStepCountStartingFrom:rangeStart
                                             to:rangeEnd
                                        toQueue:[NSOperationQueue mainQueue]
                                    withHandler:^(NSInteger numberOfSteps, NSError *error) {

                                        if (numberOfSteps > 10) {
                                            activeTime=activeTime+10;
                                        }

                                        if(rangeEnd == numberOfSteps)
                                        {
                                            [self callback:activeTime];
                                        }

                                        NSLog(@"Steps = %ld; Time = %ld",(long)numberOfSteps, (long)activeTime);
                                    }];
    }
}

- (void)callback:(NSInteger)activeTime {

    NSLog(@"Active Time = %d", activeTime);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top