如何在调用方法中设置变量 - 例如[... {here}]

时间:2015-09-03 18:01:07

标签: ios objective-c

我有这段代码,并尝试将变量NotAllSaved设置为true,但在调用saveObject返回后,该变量再次为false。

NotAllSaved=false
[healthStore saveObject:theSample withCompletion:^(BOOL success, NSError *error){
   if (!success){
       if (error.code==HKErrorAuthorizationDenied) {
           NotAllSaved=true;
       } else {
           ...    
       }
    }
}];
if (NotAllSaved) {
    // Does never come here
}

如何设置变量以便我可以在调用SaveObject之外处理错误?如果我尝试在那里弹出警报,应用程序会在显示弹出窗口之前花费大量时间。

-

添加了:

谢谢Lytic和Saheb Roy,你的答案(和一些额外的谷歌搜索)解决了我的问题,所以对我有用的解决方案是:

__block bool NotAllSaved=false;
dispatch_group_t theWaitGroup = dispatch_group_create();
dispatch_group_enter(theWaitGroup);
[HDBI.healthStore saveObject:theSample withCompletion:^(BOOL success, NSError *error){
    if (!success){
        if (error.code==HKErrorAuthorizationDenied){
            NotAllSaved=true;
        } else {
            .. .
        }
    }
    dispatch_group_leave(theWaitGroup);
}];
dispatch_group_wait(theWaitGroup, DISPATCH_TIME_FOREVER);
if (NotAllSaved) {

2 个答案:

答案 0 :(得分:1)

这是异步使用块的行为。

withCompletion:{}中包含的代码实际上在操作队列运行块之前不会执行。这通常会在检查后发生(NotAllSaved)

必须在完成块内处理错误(或者可以调用错误处理程序)

例如:

NotAllSaved=false
[healthStore saveObject:theSample withCompletion:^(BOOL success, NSError *error)
            {
                if (!success)
                {
                    if (error.code==HKErrorAuthorizationDenied)
                    {
                        NotAllSaved=true;
                    }
                    else
                    {
                        ...    
                    }
                }

                if (NotAllSaved)
                {
                   // Will execute now
                }
            }];

答案 1 :(得分:0)

这是因为这不是一个方法,它是一个以插入符号^开头的块,当你想访问一个块内的任何局部变量时,该块会生成一个变量的副本,或者更确切地想到它像这样,在块内部变量为read only,使变量读写使用此

__block BOOL NotAllSaved = false; 现在使用此__block(2个下划线)设置此项,您可以通过其引用

调用变量