我一直在尝试从中获取价值inside现在已经阻塞了几个小时,我不明白如何在完成时使用处理程序以及几乎所有内容。
这是我的代码:
+ (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]);
}];
}
所以我正在尝试 NSLogreturnString
来自downloadUserID
方法。
我首先尝试返回,然后我意识到你不能从块内返回。所以现在我一直在尝试用:(void(^)(NSString *result))handler
尝试从另一个类方法访问它。
所以我打电话downloadUserID
来自getUserID
方法,并尝试记录returnString
细绳。它只是一直趋向于零。它只是打印From get userID
没有别的。
我如何访问returnString
那是在块内downloadUserID
method?
问题不在于block
本身,问题在于实现该块是异步执行的。
在您的代码中,当您调用时handler(returnString);
该块可能仍在另一个线程上执行,因此此时您无法捕获该值。
也许您想要做的就是将该行移动到块内(可能在末尾,在右大括号之前)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)