2017-06-01 78 views
-1

我正在測試回調和塊功能。ios回調塊返回值

我在iOS中使用objective-c。

我寫回調方法的名字是「dosomethingProcessWithCompletion」。

dosomethingProcessWithCompletion做些什麼,那麼它會得到NSMutableDictionary的值,我將使用nsmutabledictionary值來檢查某些東西並返回值yes或no。

如果該值是肯定的(------- ------- AAAAA),我需要打破

爲(NSInteger的I = 0;我< myAry.count;我++) .. for循環。

並使用tryToCallBlockMethod方法返回yes。

如果該值爲否,則for循環將運行到最後一個項目並使用tryToCallBlockMethod方法返回no。

但我不知道如何編寫回調返回值。

有沒有人可以舉手?

我下面的代碼:

我AppTool聲明:

typedef BOOL(^DoMyProcessCompletion)(NSMutableDictionary *completeresult); 
+ (void) dosomethingProcessWithCompletion:(NSURL*)theUrl andUserPsd:(NSString*)psd withCompletion:(DoMyProcessCompletion) completion{ 

..... 
.... 
.. 
NSMutableDictionary *resultDic = [NSMutableDictionary dictionary]; 
if(something == YES){ 

    [resultDic setObject:[NSNumber numberWithBool:YES] forKey:@"resultDicKey"]; 
    [resultDic setObject:myData forKey:@"myDataDicKey"]; 
     }else{ 
[resultDic setObject:[NSNumber numberWithBool:NO] forKey:@"resultDicKey"]; 
    [resultDic setObject:[NSNull null] forKey:@"myDataDicKey"]; 
     } 
    completion(resultDic) 
} 

我的使用和執行功能低於:

-(BOOL) tryToCallBlockMethod{ 
    for(NSInteger i = 0 ; i < myAry.count; i++){ 
      userPsd = myAry[i];  
     [AppTool dosomethingProcessWithCompletion:[NSURL URLWithString:theUrl] andUserPsd:userPsd withCompletion:^(NSMutableDictionary *completeResult) { 

      BOOL result = [[completeResult objectForKey:@"resultDicKey"] boolValue]; 
      if(result == YES){ 
       //------- AAAAA------- 
       //------- if result is YES, will break the for look , and tryToCallBlockMethod will return YES. 
       return YES; 
      }else{ 
       //------- BBBBBBB------- 
       return NO; 
      } 
     }]; 
    } 
} 

非常感謝你。

+0

我想你完全誤解了該塊的用法。 Block通常用於異步方式,異步進程如何打破循環?如果你想要一些檢查可能會打破循環,你不應該使用塊,只需使用正常的同步過程。 –

回答

0

當您在功能中使用時,您需要返回布爾值。

-(void) tryToCallBlockMethod:(void(^)(BOOL isResult))callback{ 
     if(result == YES){ 
        callback(YES) 
       return YES; 
      }else{ 
        callback(NO) 

      } 
}