我已经尝试了几个小时,从一个块内部获取一个值,我不明白如何在完成时使用处理程序,实际上不知道该如何使用。
这是我的代码:
+ (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]);
}];
}
所以我想returnString
从downloadUserID
方法NSLog 。我首先尝试返回,然后我意识到您无法从一个块内进行返回。因此,现在我一直在尝试使用:(void(^)(NSString *result))handler
来尝试从另一个类方法访问它。
所以我downloadUserID
从getUserID
方法中调用,并尝试记录该returnString
字符串。它只是一直保持零。它只是打印From get userID
而已。
我如何访问方法returnString
块内的那个downloadUserID
?
问题不在block
于其本身,而是问题在于该块是异步执行的。
在您的代码中,在您调用handler(returnString);
该块时,该块可能仍在另一个线程上执行,因此,此时您无法捕获该值。
可能要执行的操作是将该行移动到块内(可能在结尾处,在右大括号之前)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句