【发布时间】:2014-03-22 17:24:01
【问题描述】:
我已经尝试从 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]);
}];
}
所以我正在尝试从downloadUserID 方法对returnString 进行NSLog。
我首先尝试返回,然后我意识到你不能从块内返回。所以现在我一直在尝试使用:(void(^)(NSString *result))handler 来尝试从另一个类方法访问它。
所以我从getUserID 方法调用downloadUserID,并尝试记录returnString 字符串。它只是继续为零。它只打印From get userID 而没有其他内容。
如何访问downloadUserID 方法块内的returnString?
【问题讨论】:
-
一旦你有你想要返回的值,你需要从完成处理程序内部调用
handler。
标签: ios objective-c objective-c-blocks