通过完成块传递的函数有时不会运行...如何调试

时间:2015-12-22 17:22:50

标签: ios objective-c objective-c-blocks

我正在尝试调试以下代码:

- (void) getAllDataForHKIdentifier {
...
void (^completionCopy)(NSArray *) = [completion copy];
...

    HKAnchoredObjectQuery *newQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType predicate:predicate anchor:anchor limit:HKObjectQueryNoLimit resultsHandler:^(HKAnchoredObjectQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable sampleObjects, NSArray<HKDeletedObject *> * _Nullable deletedObjects, HKQueryAnchor * _Nullable newAnchor, NSError * _Nullable error) {

                if([sampleObjects count] > 0){
                    NSLog(@"for hkquantity type = %@ is block null? %d is block nil? %d those are the answers", theHKIdentifier, [completion isKindOfClass: [NSNull class]], completion==nil);

                    NSLog(@"here is direct call to nonsense");
                    [self nonsenseTestFunc:sampleObjects];

                    // this often fails to run although completion block is neither nil nor NSNull so far as I can tell
                    NSLog(@"here is completion object %@", completion);
                    completionCopy(sampleObjects);

                    NSLog(@"tktktk for source %@ there are %d sources and those sources are %@", useSource, (int)[sampleObjects count], sampleObjects);
                }


                [[ODLogManager sharedManager] logString:[NSString stringWithFormat:@"tktktk setting anchor from %@ to %@ for category %@ when results count is %d", anchor, newAnchor, theHKIdentifier, (int)[sampleObjects count]] forCategory:ODLoggingAileen];
                [[CoreManager sharedManager] setHealthKitAnchorForIdentifier:theHKIdentifier toValue:newAnchor];
            }];

            [healthStore executeQuery:newQuery];

...
}

上面的代码位于同一个类实例中由以下函数调用的函数中:

            dispatch_group_async(dispatchGroup, queue, ^{
                    [self getAllDataForHKIdentifier: hkType withCompletion:^(NSArray *results) {
                    [self nonsenseTestFunc:results];
                }];
            });

上面是我调用getAllDataForHKIdentifier的唯一地方,因此completionCopy块也应该运行此nonsenseTestFunc。但是现在只运行它的时间大约是if语句中其余代码运行的一半。运行控制语句中其他语句的另一半时间,没有completionCopy已运行的迹象。

这是我到目前为止所尝试的内容:

  • 从日志语句中可以看出,我已经尝试检查完成黑色是否为nil或NSNull,但这些都返回false。是否有另一种方法来确定完成块是否有故障或确定完成块的内容?
  • 我认为即使我使用ARC也可能存在一些内存覆盖问题/泄漏问题,所以我复制了completion参数,然后在查询调用中运行此副本而不是原始版本块。这并未改变错误。

为什么会发生这种情况? 似乎completion块必须在某个地方丢失或被删除,但是如何或为什么?感谢任何输入。

1 个答案:

答案 0 :(得分:-1)

对completionCopy的唯一调用是在if(samplesObjects.count&gt; 0)内。所以很明显,如果该计数为零,则不会被调用。