iOS没有看到块返回的预期值

时间:2014-01-17 22:46:57

标签: ios objective-c-blocks

我有以下代码,但我从未看到最后返回runStepCountTotal。总增量,但最后一个NSLog行实际上是在块完成之前返回的。

我意识到我错误地使用了这个块,但是想知道是否有人能够向我解释如何实现这个目标?

非常感谢。

- (NSInteger)getRunSteps
{
__block NSInteger runstepCountTotal = 0;

if([CMMotionActivityManager isActivityAvailable])
{
    CMMotionActivityManager *cm = [[CMMotionActivityManager alloc] init];
    CMStepCounter *sc = [[CMStepCounter alloc] init];
    NSDate *today = [NSDate date];
    [cm queryActivityStartingFromDate:[self startDateOf6DayAgo] toDate:today toQueue:[NSOperationQueue mainQueue] withHandler:^(NSArray *activities, NSError *error){

        for(int i=0;i<[activities count]-1;i++)
        {
            CMMotionActivity *a = [activities objectAtIndex:i];
            if (a.running)
            {
                [sc queryStepCountStartingFrom:a.startDate to:[[activities objectAtIndex:i+1] startDate] toQueue:[NSOperationQueue mainQueue] withHandler:^(NSInteger numberOfSteps, NSError *error)
                {
                    runstepCountTotal = runstepCountTotal+numberOfSteps;
                    NSLog(@"Current Total is %ld",(long)runstepCountTotal);
                }];
            }
        }
    }];
}
NSLog(@"Final Total is %ld",(long)runstepCountTotal);
return runstepCountTotal;
}

2 个答案:

答案 0 :(得分:1)

阅读queryActivityStartingFromDate:toDate:toQueue:withHandler:方法的文档。

  

<强>讨论
  此方法异步运行,立即返回并将结果传递到指定的处理程序块。

您的方法在调用处理程序块之前很久就会返回。

答案 1 :(得分:0)

假设我们应该执行一些异步方法

- (void)loadPropertyAsynchronouslyWithCompletion:(void (^)(int val))completion;

还有一些要更新的属性:

@property int value;

然后要获得它的价值,我们需要这样的东西:

[self loadPropertyAsynchronouslyWithCompletion:^(int val){
    self.value = val;
}];

我跳过了一些多线程的特定时刻,以使想法更清晰

修改


更接近你的榜样......

异步更新用户界面的某些UILabel元素的方法步骤数可以是这样的:

- (void)updateSomeLabel:(UILabel *)label withNumberOfStepsStartingFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
    if (![CMStepCounter isStepCountingAvailable]) {
        return;
    }

    CMStepCounter *stepCounter = [[CMStepCounter alloc] init];

    [stepCounter queryStepCountStartingFrom:fromDate to:toDate toQueue:[NSOperationQueue mainQueue] withHandler:^(NSInteger numberOfSteps, NSError *error) {
        if (!error) {
            label.text = [NSString stringWithFormat:@"fromDate: %@, toDate:%@, numberOfSteps:%d", fromDate, toDate, numberOfSteps];
        } else {
            NSLog(@"Unresolved error:%@, %@", error, [error userInfo]);
        }
    }];
}