内部块的返回值(Objective-C)

我一直试图从一个块里面获取一个值几个小时,我无法理解如何在完成时使用处理程序以及几乎所有内容。
这是我的代码:

+ (void)downloadUserID:(void(^)(NSString *result))handler { //Now redirect to assignments page __block NSMutableString *returnString = [[NSMutableString alloc] init]; //'__block' so that it has a direct connection to both scopes, in the method AND in the block NSURL *homeURL = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"]; NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL]; [requestHome setHTTPMethod:@"GET"]; // this looks like GET request, not POST [NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError) { // do whatever with the data...and errors if ([homeData length] > 0 && homeError == nil) { NSError *parseError; NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError]; if (responseJSON) { // the response was JSON and we successfully decoded it //NSLog(@"Response was = %@", responseJSON); } else { // the response was not JSON, so let's see what it was so we can diagnose the issue returnString = (@"Response was not JSON (from home), it was = %@", [[NSMutableString alloc] initWithData:homeData encoding:NSUTF8StringEncoding]); //NSLog(returnString); } } else { //NSLog(@"error: %@", homeError); } }]; //NSLog(@"myResult: %@", [[NSString alloc] initWithData:myResult encoding:NSUTF8StringEncoding]); handler(returnString); } - (void)getUserID { [TClient downloadUserID:^(NSString *getIt){ NSLog([NSString stringWithFormat:@"From get userID %@", getIt]); }]; } 

所以我试图从downloadUserID方法NSLog的returnString 。 我第一次尝试返回,然后我意识到你不能从一个块里面做出回报。 所以现在我一直在尝试使用:(void(^)(NSString *result))handler来尝试从另一个类方法访问它。

所以我从getUserID方法调用downloadUserID ,并尝试记录returnString字符串。 它只是一无所获。 它只是打印From get userID而不是其他内容。

如何访问downloadUserID方法块内的returnString

问题不在于block本身,问题在于意识到块是异步执行的。

在你的代码中,当你调用handler(returnString); 该块可能仍在另一个线程上执行,因此此时无法捕获该值。

可能你想要做的是在块内移动该行(可能在结束时,在结束括号之前)。